数组ID匹配后按大陆分类国家异常:代码仅添加最后值
问题分析与解决
问题背景
现有数组定义:
europe= []; northAmerica = []; southAmerica = []; asia = [];
以及两个数据数组:
arr1 = [1,3]; arr2 = [ { country: "Brazil", id: 1, continent: "southAmerica" }, { country: "Germany", id: 2, continent: "europe" }, { country: "India", id: 3, continent: "asia" }, { country: "China", id: 4, continent: "asia" }, ];
需求:当arr2中对象的id存在于arr1时,将该对象的country存入对应大陆的数组。
尝试以下代码后,仅最后一个符合条件的值被存入对应数组:
arr2.map((item) => { if (arr1.find((id) => id === item.id)) { if (item.continent === "southAmerica") { southAmerica.push(item.country); } if (item.continent === "asia") { asia.push(item.country); } } });
问题原因
- 数组被意外覆盖:最可能的核心原因是代码其他位置重新给
southAmerica/asia等数组赋值(比如再次执行southAmerica = []),导致之前push的内容被清空,最终只剩最后一次添加的值。 map方法误用:map的设计目的是返回新数组,用来做无返回值的遍历操作属于风格问题,虽不会直接导致数据丢失,但不符合方法语义。find效率低下:用find判断id是否存在会遍历整个数组直到找到匹配项,虽不引发当前问题,但会影响性能。
解决方法
1. 排查数组覆盖问题
检查代码中所有涉及大陆数组的部分,确保southAmerica、asia等数组只在初始化时赋值一次,后续仅通过push添加元素,不要重新赋值。
2. 优化代码逻辑
用Set提升id查找效率,同时用更简洁的方式映射大陆数组,避免冗余判断:
// 将arr1转为Set,实现O(1)时间复杂度的id存在性判断 const validIds = new Set(arr1); // 用forEach做遍历,更符合无返回值操作的场景 arr2.forEach(item => { if (validIds.has(item.id)) { // 方式一:用switch处理所有大陆分支 switch(item.continent) { case 'southAmerica': southAmerica.push(item.country); break; case 'asia': asia.push(item.country); break; case 'europe': europe.push(item.country); break; case 'northAmerica': northAmerica.push(item.country); break; } // 方式二:用对象映射简化代码(更推荐) // const continentArrays = { southAmerica, asia, europe, northAmerica }; // 可选链避免不存在的大陆触发报错 // continentArrays[item.continent]?.push(item.country); } });
3. 验证结果
执行后正确结果应为:
southAmerica = ["Brazil"]asia = ["India"]
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

