javascript - 为什么扁平化不起作用?

标签 javascript arrays node.js flatten

我已经阅读了 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/

相关文章:

javascript - 如何在nodeJS中向mysql添加map对象?

javascript - 为什么这个 Vue 计算属性不是响应式的?

javascript - 在 AlertifyJS 中使用 If 语句

c - 多维数组分配

arrays - 如何: REST API that passes and array of key/value pairs

javascript - 大数字的 Node.js 输出格式

javascript - 使用 React Router PrivateRoute 处理 Refreshtoken

javascript - 使用 Babel 将 ES6 模块转换为 ES5 AMD 模块,未按预期工作

arrays - 创建一个范围内的非空白单元格值列表?

node.js - 如何在代码中解析带引号的搜索查询