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

如何通过cca3编码从countryList获取德国的边境国家名称?

修复代码:通过cca3编码获取边境国家名称

需求概述

通过德国的边境国家cca3编码(AUT、BEL、FRA),从countryList数组中匹配对应的国家名称,期望结果为["France", "Austria", "Belgium"]。

修复后的代码

const countryList = [
  { name: 'France', cca3: 'FRA' },
  { name: 'Austria', cca3: 'AUT' },
  { name: 'Belgium', cca3: 'BEL' },
  { name: 'Brazil', cca3: 'BRA' }
];

const country = [
  { name: { common: 'Germany' } },
  { cca3: "DEU" },
  { borders: ['AUT', 'BEL', 'FRA'] }
];

const getCountryBordersName = () => {
  // 动态找到country数组中包含borders的元素
  const targetBorders = country.find(item => item.borders)?.borders || [];
  // 遍历编码,匹配对应国家名称
  return targetBorders.map(code => {
    const matched = countryList.find(country => country.cca3 === code);
    return matched ? matched.name : null;
  }).filter(name => name !== null); // 过滤无效匹配结果
};

console.log(getCountryBordersName()); // 输出: ["France", "Austria", "Belgium"]

原代码的错误点分析

  • 数组索引错误:原代码用country[0].borders,但borders字段在country数组的第三个元素(索引2),直接硬编码索引易出错,改用find动态查找更健壮。
  • 赋值代替比较:find回调里的code.item = code是赋值语句,逻辑完全错误,正确应该用country.cca3 === code做全等匹配。
  • 返回函数而非结果:原函数getCountryBordersName返回的是borderName函数本身,没有执行它,导致控制台输出函数引用而非预期结果。
  • 未处理匹配失败场景:若某个编码在countryList中不存在,原代码会返回undefined,修复后添加了空值处理和过滤,确保结果仅包含有效名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:50:26