You need to enable JavaScript to run this app. JavaScript使用for循环遍历不同长度数组提取匹配国家对象
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript使用for循环遍历不同长度数组提取匹配国家对象

JavaScript嵌套循环匹配需求实现

原代码存在的问题

  • if判断语句后附带的冗余分号;会直接截断if的逻辑关联,后续代码块会变为无条件执行
  • 循环变量i、j未通过let声明,会泄漏为全局变量,造成作用域污染
  • 缺少匹配成功后将目标对象存入arr3的核心逻辑

完整可运行代码

const arr1 = ["GR", "DE", "AF", "FR"];
const arr2 = [
  { "code": "AF", "code3": "AFG", "name": "Afghanistan" },
  { "code": "GQ", "code3": "GNQ", "name": "Equatorial Guinea" },
  { "code": "FI", "code3": "FIN", "name": "Finland" },
  { "code": "FR", "code3": "FRA", "name": "France" },
  { "code": "GF", "code3": "GUF", "name": "French Guiana" },
  { "code": "PF", "code3": "PYF", "name": "French Polynesia" },
  { "code": "GA", "code3": "GAB", "name": "Gabon" },
  { "code": "GM", "code3": "GMB", "name": "Gambia (the)" },
  { "code": "GE", "code3": "GEO", "name": "Georgia" },
  { "code": "GH", "code3": "GHA", "name": "Ghana" }
];

let arr3 = [];

for (let i = 0; i < arr1.length; i++) {
  for (let j = 0; j < arr2.length; j++) {
    // 移除原if后的多余分号,使用全等匹配避免子串误判
    if (arr2[j].code === arr1[i]) {
      arr3.push(arr2[j]);
    }
  }
}

运行结果

执行后arr3的值完全符合预期:

[
  { code: 'AF', code3: 'AFG', name: 'Afghanistan' },
  { code: 'FR', code3: 'FRA', name: 'France' }
]

拓展说明:如果需要避免重复存入相同code的对象,可在push前增加判断:if (!arr3.some(item => item.code === arr2[j].code)) arr3.push(arr2[j]),适合arr2存在重复数据的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 11:57:02