4

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 at the second iteration transitions[0].property equals "background-color"?

3 Answers 3

10

Because you are storing a reference to transitionInitial, not a copy of it. transitionInitial points to an object in memory, and you are storing a reference to this object in transitions[k]. Regardless of the iteration you are at, you are always changing the same object.

Sign up to request clarification or add additional context in comments.

Comments

3

It's because both values in your transitions array are pointing at the same object. During the execution of your code you produce one object that has three different references (transitionInitial, transistions[0], & transistions[1]).

During the first iteration of the loop, transistions[0] is set to reference the transitionInitial object. Then the property property of that object is set to the value "color". During the second iteration transitions[1] is set to reference the same object as transitionInitial and transitions[0]. You then reset the property's value to "background-color".

To solve this create different objects for each of your array indexes:

// 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);
}​

Comments

0

Does it have anything with this to do maybe? for ( var k = 0; k < rules.length; k++) Try changing the timer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.