Javascript array objects

http://jsfiddle.net/gfuKS/5/

var transitionInitial = {property: "none"};
var rules = ["color", "background-color"];
var transitions = [];
for ( var k = 0; k < rules.length; k++)
{
    transitions[k] = transitionInitial;
    transitions[k].property = rules[k];
    alert(transitions[0].property);
}​

Why is the second iteration of [0] .property equal to "background-color"?

+5
source share
3 answers

Because you keep the link to transitionInitial, not a copy of it. transitionInitialpoints to an object in memory, and you keep a reference to that object in transitions[k]. Regardless of the iteration you are in, you are always changing the same object.

+10
source

This is because both values ​​in your array transitionspoint to the same object. At runtime, you create one object with three different references ( transitionInitial, transistions[0]and transistions[1]).

transistions[0] transitionInitial. property "color". transitions[1] , transitionInitial transitions[0]. reset property "background-color".

, :

// Not needed anymore:
// var transitionInitial = {property: "none"};
var rules = ["color", "background-color"];
var transitions = [];
for ( var k = 0; k < rules.length; k++) {
  transitions[k] = {};
  transitions[k].property = rules[k];
  alert(transitions[0].property);
}​
+3

Maybe he has something? for ( var k = 0; k < rules.length; k++) Try changing the timer.

0
source

All Articles