www.webdeveloper.com
Results 1 to 3 of 3

Thread: Storing objects in Array Behave Badly

  1. #1
    Join Date
    May 2013
    Posts
    2

    Storing objects in Array Behave Badly

    Here's the code:
    Code:
    // generates a nice bright yellow to oranges palette
    function genPalette()
    {
    	var icols = 0;
    	var color = new Object();
    	color.r = 0;
    	color.g = 0;
    	color.b = 0;
    	// Make 154 color palette starting with black
    	palette[icols] = color;
    	icols++;
    	for( ; color.r < 255; color.r += 5) {
    		palette[icols] = color;
    		alert("Here" + palette[0].r);
    		icols++;
    		color.g = Math.floor(color.r / 2); //Make and orange
    		palette[icols] = color;
    		icols++;
    		color.b = Math.floor(color.r / 4); //Make a yellow
    		icols++;
    	}
    	return icols;
    }
    
    var palette = new Array(155);
    genPalette();
    When the following code is run palette[0].r continues to change to whatever palette[icols].r is. It's as if the whole array changes whenever one element is changed. I'm new to javascript, but I've used C++ a lot. So what's going on here?

  2. #2
    Join Date
    Jul 2003
    Location
    The City of Roses
    Posts
    2,503
    If you used C++ a lot, then you probably know about objects. They're passed and assigned by reference (by pointer). In your JavaScript, you only ever created one object, and you're assigning the same object reference to every element of the array. That's why changing one element changes them all... because they're all references to the same object.
    for(split(//,'))*))91:+9.*4:1A1+9,1))2*:..)))2*:31.-1)4131)1))2*:3)"'))
    {for(ord){$i+=$_&7;grep(vec($s,$i++,1)=1,1..($_>>3)-4);}}print"$s\n";

  3. #3
    Join Date
    May 2013
    Posts
    2
    Thank you very much for taking the time to answer my question. That solved my problem!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles