我已经阅读了 MDN 中如何展平数组的代码在JS中。并且工作正常,但我不明白为什么在这种情况下不起作用:
const data = [null, ['a', 'b', 'c']]
const flattened = data.reduce((acc, cur) => {
if(null != cur)
acc.concat(cur)
}, [])
这个错误:
TypeError: Cannot read property 'concat' of undefined
如何纠正这个问题?
最佳答案
传递给.reduce()的函数没有返回任何值
const data = [null, ['a', 'b', 'c']]
const flattened = data.reduce((acc, cur) => {
if (cur !== null)
acc = acc.concat(cur);
return acc
}, []);
console.log(flattened);
关于javascript - 为什么扁平化不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43959195/