为何对象数组上的map操作被跳过、回调逻辑完全未执行
异常根因
当前代码存在数组操作逻辑错误:
- 代码中定义的
countriesAtoH是空数组,但循环内使用countriesAtoH[c] = countries[c]的方式赋值时,c是国家名称构成的字符串(如"Afghanistan"),并非数组要求的0起始数字索引。 - JS的数组本质是特殊对象,支持挂载任意名称的自定义属性,但这类属性不会被计入数组的有效元素集合,也不会被
map、forEach等数组原生方法遍历。调试时看到数组“已存储对应国家对象”,只是控制台把手动挂载的自定义属性展示在了数组展开项中,此时数组自身的length依然为0,直接调用map自然不会触发回调,最终返回的options长度为0。
修复方法
将数组存值逻辑从自定义属性赋值,改为往数组有效位置追加元素即可,两种实现可选:
- 保留原有循环结构,将循环内的赋值语句替换为
countriesAtoH.push(countries[c]) - 移除冗余的手动建数组、遍历塞值逻辑,直接通过对象值遍历完成过滤、映射,代码更简洁
修正后代码(保留原循环结构)
const countries = { Afghanistan: { countryId: 0, name: "Afghanistan" }, Albania: { countryId: 1, name: "USA" }, Algeria: { countryId: 99, name: "Canada" } } export const countryOptions = () => { let countriesAtoH = []; Object.keys(countries).forEach((c) => { if (countries[c].countryId <= 97) { countriesAtoH.push(countries[c]); } }); const options = countriesAtoH.map(country => { return { text: { type: "plain_text", text: country.name, }, value: country.countryId } }); return options; }
更简洁的实现版本
export const countryOptions = () => { return Object.values(countries) .filter(item => item.countryId <= 97) .map(country => ({ text: { type: "plain_text", text: country.name, }, value: country.countryId })) }
内容的提问来源于stack exchange,提问作者PositiveGuy
相关产品推荐
相关产品推荐

