0

when I try to set a value in an array in javascript, all the other "adjacent" values change as well.

var screenData = [];
function init() {
    var properties = { "property": "value" }
    for( i = 0; i < 35; i++ ) {
        var row = [];
        for( j = 0; j < 19; j++ ) {
            row.push(properties);
        }
        screenData.push(row);
    }
}
init();
screenData[0][0].property = "othervalue";
alert(screenData[0][1].property);

The alert will return othervalue although it should be value :(

Did I just oversee something or is this a bug?

Any help would be appreciated :3

Creeps
  • 21
  • 4

4 Answers4

1

This is because you reference the same object (properties) thus each time you modify property it is updated everywhere.

function init() {
    for( i = 0; i < 35; i++ ) {
        var row = [];
        for( j = 0; j < 19; j++ ) {
            row.push({ property: 'value' });
        }
        screenData.push(row);
    }
}
axelduch
  • 10,769
  • 2
  • 31
  • 50
0

That's because you are pushing the same object in each iteration, you should clone the object and then push the cloned object. Currently all the array's elements refer to the same object.

Community
  • 1
  • 1
Ram
  • 143,282
  • 16
  • 168
  • 197
0

This is not a bug. You are pushing a reference to the the properties object into your array. This means your array contains several references to the same object. You can solve this by resetting the properties variable inside the for loop.

function init() {
   for( i = 0; i < 35; i++ ) {
        var row = [];
        for( j = 0; j < 19; j++ ) {
            var properties = { "property": "value" }
            row.push(properties);
        }
        screenData.push(row);
    }
}
bengro
  • 1,004
  • 10
  • 19
0

I think, instead this:

for( j = 0; j < 19; j++ ) {
        row.push(properties);
    }
screenData.push(row);

It could be:

for( j = 0; j < 19; j++ ) {
        row.push(_clone(properties));
    }
screenData.push(row);

Where _.clone(object) is Underscore library function: UnderScore _clone references

Note that, as you can read here, nested objects (not in this case, because this is string) are referenced not copied.

Radek Anuszewski
  • 1,812
  • 8
  • 34
  • 62