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

如何避免For循环合并数组时生成重复结果?附嵌套数组需求

数组配对合并问题的解决方案

问题背景

现有两个数组:

let nameList = ["John","Brenda","Sabrina","Ray","Jacob"];
let ageList = [23, 29, 30, 23, 25];

需求是将同位置的姓名与年龄配对,生成嵌套数组:[['John', 23],['Brenda',29],['Sabrina',30],['Ray',23],['Jacob',25]]。

编写的combineData函数如下:

function combineData (nameArray,ageArray,combArray){
    let tempComb=[];
    for (let i=0;i<nameArray.length;i++) {
        tempComb.push(nameArray[i]);
        tempComb.push(ageArray[i]);
        combArray.push(tempComb);
    }
}

执行后得到重复的错误结果:

[ [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ],
  [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ],
  [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ],
  [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ],
  [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ] ]

错误原因

tempComb数组在循环外部声明,整个循环过程中始终是同一个数组引用。每次循环往tempComb里追加新元素,再把这个数组的引用添加到combArray中。最终combArray里的所有元素都是指向同一个数组的指针,所以显示的内容完全重复,且是所有元素的累加结果。

修复方案

方案1:修改原函数

将tempComb的声明移到循环内部,每次循环创建一个新数组,确保每次添加到combArray的都是独立的新数组:

function combineData (nameArray, ageArray, combArray){
    for (let i=0; i<nameArray.length; i++) {
        let tempComb = []; // 每次循环创建新数组
        tempComb.push(nameArray[i]);
        tempComb.push(ageArray[i]);
        combArray.push(tempComb);
    }
}

// 调用示例
let result = [];
combineData(nameList, ageList, result);
console.log(result); // 输出目标嵌套数组

方案2:使用map方法简化实现

利用数组的map方法可以更简洁地完成配对,无需额外声明临时数组:

const combinedArray = nameList.map((name, index) => [name, ageList[index]]);
console.log(combinedArray); // 输出目标嵌套数组

map会遍历nameList的每个元素,同时通过index获取ageList对应位置的元素,返回由这两个元素组成的新数组,最终生成符合需求的嵌套数组。

内容的提问来源于stack exchange,提问作者Juan Yeremia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:27:32