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

使用Lodash遍历数组遇到问题,期望得到指定结果

解决Lodash遍历数组无法收集返回值的问题

嘿,我看你是想通过selectedItems里的索引,把items中对应元素的name收集到selectedValues里对吧?问题出在你用错了Lodash的方法——_.forEach的返回值始终是你遍历的原数组(也就是这里的selectedItems),不管你在回调函数里return什么,都不会改变它的返回结果,这就是为什么你最后拿到的selectedValues还是[0,1],而不是期望的['A','B']。

正确的做法:用_.map替代_.forEach

_.map的作用就是遍历数组,把每个元素经过回调处理后的返回值收集起来,形成一个新数组返回,完全匹配你的需求。修改后的代码如下:

const items = [{ id: '1', name: 'A' }, { id: '2', name: 'B' }, { id: '3', name: 'C' }, { id: '4', name: 'D' }, { id: '5', name: 'E' }]
var selectedItems = [0, 1]
// 替换为_.map
const selectedValues = _.map(selectedItems, function(val) {
    console.log('val -', val)
    console.log('items[val] -', items[val].name)
    return items[val].name
})
console.log('selectedValues - ', selectedValues) // 输出: selectedValues -  ["A", "B"]

备选方案:用_.forEach手动收集值

如果你一定要用_.forEach,也可以自己初始化一个空数组,在回调里把需要的值push进去,只是这种写法不如_.map简洁:

const items = [{ id: '1', name: 'A' }, { id: '2', name: 'B' }, { id: '3', name: 'C' }, { id: '4', name: 'D' }, { id: '5', name: 'E' }]
var selectedItems = [0, 1]
const selectedValues = [] // 初始化空数组
_.forEach(selectedItems, function(val) {
    console.log('val -', val)
    console.log('items[val] -', items[val].name)
    selectedValues.push(items[val].name) // 手动添加值
})
console.log('selectedValues - ', selectedValues) // 同样输出: ["A", "B"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:22:45