You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中如何将数组推入另一数组?循环填充多维数组遇覆盖问题

Hey there! Let's tackle your two JavaScript questions one by one.

问题1:在JavaScript中如何将一个数组推入另一个数组中?

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]
    
问题2:多维数组填充时data字段被覆盖的问题

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:04:08