【问题标题】:Why flatten isn't working?为什么扁平化不起作用?
【发布时间】:2017-10-13 00:58:22
【问题描述】:

我已经阅读了如何在 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

如何解决这个问题?

【问题讨论】:

  • 如果目的是过滤空值(或者可能是假值?),您也可以使用 Array#sort:data.filter(cur => cur !== null).reduce((acc, cur) => acc.concat(cur), []);
  • @naomik 虽然主题已在链接问题中得到解决,但问题中的具体问题并未通过链接问题的答案得到解决。是否存在解决 Array.prototype.reduce() 回调函数未返回值的问题/答案?
  • @thibmaek 我只想在数组上迭代一次,这就是为什么我只选择reduce。如果我在通过 reduce 方法再次迭代之前使用了过滤器。

标签: javascript arrays node.js flatten


【解决方案1】:

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

【讨论】:

  • @LucasAlmeidaCarotta 另外acc.concat(cur) 应该是acc = acc.concat(cur)acc.push(...cur)
猜你喜欢
  • 1970-01-01
  • 2014-09-30
  • 2021-10-01
  • 2016-11-09
  • 2018-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
相关资源
最近更新 更多