5

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

为什么在第二次迭代时 transitions[0].property 等于“背景颜色”?

4

3 回答 3

10

因为您存储的是对 的引用transitionInitial,而不是它的副本。transitionInitial指向内存中的一个对象,并且您将对该对象的引用存储在transitions[k]. 无论您处于何种迭代中,您总是在更改同一个对象。

于 2012-05-16T19:18:17.663 回答
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);
}​
于 2012-05-16T19:25:21.607 回答
0

它可能与此有关吗?for ( var k = 0; k < rules.length; k++) 尝试更改计时器。

于 2012-05-16T19:18:07.680 回答