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

JS比对鞋码数组时报Cannot read properties of undefined (reading 'size')

错误原因

  • for...in遍历数组得到的arr1Item是数组索引,arr1总共有14个元素,索引范围0~13,而arr2只有9个元素,索引最大为8。当循环到索引≥9时,arr2[arr1Item]就是undefined,访问undefined.size自然抛出类型错误。你觉得console.log(arr2[arr1Item])能正常输出,是因为前9次循环索引没超过arr2长度,确实能拿到对象,后面几次已经输出undefined了,只是你没注意到,直到访问.size才触发报错。
  • 匹配逻辑错误:你现在是按相同索引位置对比两个数组的元素,不是校验arr2全局是否存在对应鞋码,而且arr1的size带US 前缀,直接匹配也无法对应上arr2的纯数字鞋码。

修复方案

先把arr2的鞋码转成Map做快速查找,再遍历arr1匹配即可,时间复杂度从O(n²)降到O(n):

const newArr = []
const arr1 = [
    { size: 'US 3' },
    { size: 'US 4' },
    { size: 'US 5' },
    { size: 'US 6' },
    { size: 'US 7' },
    { size: 'US 8' },
    { size: 'US 9' },
    { size: 'US 10' },
    { size: 'US 11' },
    { size: 'US 12' },
    { size: 'US 13' },
    { size: 'US 14' },
    { size: 'US 15' },
    { size: 'US 16' }
]
const arr2 = [
    { size: '4', cost: '170' },
    { size: '6', cost: '75' },
    { size: '7', cost: '75' },
    { size: '8', cost: '78' },
    { size: '9', cost: '80' },
    { size: '10', cost: '85' },
    { size: '11', cost: '73' },
    { size: '12', cost: '77' },
    { size: '14', cost: '100' }
]

// 构建鞋码映射表
const sizeMap = new Map(arr2.map(item => [item.size, item]))

// 遍历匹配
for (const item of arr1) {
    // 提取arr1鞋码的数字部分
    const pureSize = item.size.split(' ')[1]
    newArr.push(sizeMap.get(pureSize) || { size: '-' })
}

console.log(newArr)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:27:02