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"?
The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
There are 3 popular methods which can be used to insert or add an object to an array. The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method.
{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.
To initialize an array of objects, use the Array() constructor to create an array filled with N empty elements and use a for loop to iterate over the array assigning each element to an object. Copied! const arr2 = new Array(2); for (let i = 0; i < arr2.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With