为何扁平化不起作用?

时间:2017-05-14 00:16:37

标签: javascript arrays node.js flatten

我已经阅读了如何在JS中MDN中展平数组的代码。并且工作正常,但我不明白为什么在这种情况下没有工作:

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

如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

传递给.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);