使用 reduce 函数从数组创建新对象时无法获得正确的结果
Not able to get the correct result when using reduce function to create a new object from array
这是我的尝试,我试图从数组值创建一个新对象,但得到的结果是:two
而不是新对象。谁能帮我清楚地了解 reduce 功能?
const arr = ['one', 'two']
function fn() {
return arr.reduce((obj, val) => obj[val] = val , {});
}
console.log(fn());
//expecting: {one:'one', two:'two'} but getting 'two'
你的reducer函数returnsval
(最后处理的元素)而不是obj
(累加器),试试:
const arr = ['one', 'two']
function fn() {
return arr.reduce((obj, val) => { obj[val] = val; return obj; } , {});
}
console.log(fn());
这是我的尝试,我试图从数组值创建一个新对象,但得到的结果是:two
而不是新对象。谁能帮我清楚地了解 reduce 功能?
const arr = ['one', 'two']
function fn() {
return arr.reduce((obj, val) => obj[val] = val , {});
}
console.log(fn());
//expecting: {one:'one', two:'two'} but getting 'two'
你的reducer函数returnsval
(最后处理的元素)而不是obj
(累加器),试试:
const arr = ['one', 'two']
function fn() {
return arr.reduce((obj, val) => { obj[val] = val; return obj; } , {});
}
console.log(fn());