JS中如何将数组推入另一数组?循环填充多维数组遇覆盖问题
Hey there! Let's tackle your two JavaScript questions one by one.
There are a few common, practical ways to do this, depending on whether you want to modify the original array or create a brand new one:
Modify the original array with
push()+ spread operator
This is my go-to for most scenarios—it's clean and efficient. The spread operator (...) expands the elements of the source array so they get added as individual items to the target array:const targetArray = [1, 2, 3]; const sourceArray = [4, 5, 6]; targetArray.push(...sourceArray); // targetArray now becomes [1, 2, 3, 4, 5, 6]Create a new array with
concat()
If you don't want to alter the original array,concat()combines multiple arrays and returns a fresh one without touching the originals:const targetArray = [1, 2, 3]; const sourceArray = [4, 5, 6]; const newCombinedArray = targetArray.concat(sourceArray); // newCombinedArray is [1, 2, 3, 4, 5, 6], targetArray stays [1,2,3]Old-school
push.apply()(not recommended for large arrays)
Before ES6, this was a common trick, but it has limits with very large arrays (due to browser argument length restrictions):const targetArray = [1, 2, 3]; const sourceArray = [4, 5, 6]; Array.prototype.push.apply(targetArray, sourceArray); // targetArray becomes [1, 2, 3, 4, 5, 6]
Let's break down what's happening here: you're reusing the same aux array variable across every loop iteration. All the objects you push into array have their data property pointing to the exact same array reference. So when you update aux each time through the loop, you're actually modifying that single underlying array—this is why all your data fields end up showing the final loop's value.
To fix this, you need to create a new array for each iteration instead of reusing aux. Here are two straightforward fixes:
Fix 1: Declare aux inside the loop
Move the aux variable declaration inside the for loop so a fresh array is created every time:
var array = []; for(i=0;i<10;i++){ var aux = [i,i+1,i+2]; // New array created in each loop cycle array.push({ name:i, data:aux }); }
Fix 2: Skip the aux variable entirely (even cleaner)
You can directly define the array inside the object you push, removing the need for the aux variable altogether:
var array = []; for(i=0;i<10;i++){ array.push({ name:i, data: [i, i+1, i+2] // Fresh array created with each object }); }
Either approach ensures each object in array has its own independent data array, so they won't overwrite each other anymore.
内容的提问来源于stack exchange,提问作者Jesus

