I'm trying to take an array, inArray
, that changes with each iteration of a for()
loop and push it to a multidimensional array, medArray
. There are two different methods below that are slightly different and one achieves the goal whereas the second outputs medArray
such that is has three arrays within it and they are all equal to the last iteration of inArray
.
I'm confused as to why this works:
var inArray = [1, 2, 3];
var medArray = [];
for(i = 0; i < 3; i++){
inArray[i] += 1;
//The difference is this line below
var test = [inArray[0], inArray[1], inArray[2]];
medArray.push(test)
console.log(medArray);
}
But this doesn't work:
var inArray = [1, 2, 3];
var medArray = [];
for(i = 0; i < 3; i++){
inArray[i] += 1;
//The difference is this line below
var test = inArray;
medArray.push(test)
console.log(medArray);
}
When I individually assign the values of test
to be the individual value of inArray
it works but when I assign the two arrays to be equal, it doesn't work. What is happening?
the second outputs
medArray
such that is has three arrays within it and they are all equal to the last iteration ofinArray
.
Actually, the second code block pushes the same array to medArray
three times. When you say temp = inArray
that doesn't create a copy of the array, it creates another reference to the same array. (So if, after the loop, you were to say medArray[0][0] = 10
you'd find that medArray[1][0]
and medArray[2][0]
now both equal 10
too, because medArray[0]
, medArray[1]
and medArray[2]
all reference the same array.)
If you want to make a copy of the inArray
array then use the array .slice()
method :
var temp = inArray.slice();
Then temp
would be a new array that has the same elements as inArray
. Which is what you did in your first code block with test = [inArray[0], inArray[1], inArray[2]];
.
Or you can omit the temp
variable and just say:
medArray.push(inArray.slice());
( .slice()
can also be used to copy just a portion of an array if you call it with arguments, but called with no arguments it copies the whole array.)
In context:
var inArray = [1, 2, 3]; var medArray = []; for(var i = 0; i < 3; i++){ inArray[i] += 1; medArray.push(inArray.slice()); } console.log(medArray);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.