【问题标题】:Unable to use array on reduce无法在reduce上使用数组
【发布时间】:2021-11-25 05:01:11
【问题描述】:
Const people = [ { name: 'siddiq', age: 20} , { name: 'anas', age: 19}]

Const arr = people.reduce((acc, curr) => acc.push(curr.age), [])

它不工作。我想要的是创建一个只有年龄的数组...??

【问题讨论】:

  • 这是const,而不是Const
  • 你为什么使用reduce?这就是map 的用途。
  • “它不工作”究竟是什么意思? 任何事情会发生吗?是否报告错误?
  • 在第一次迭代中push返回数组的长度,在下一次迭代中变成acc的值,然后push不是那个数的方法。
  • 每次reduce迭代都需要返回累加器(acc)。

标签: javascript arrays reduce


【解决方案1】:

你应该使用 map() 代替:

const people = [ { name: 'siddiq', age: 20} , { name: 'anas', age: 19}]

const arr = people.map(p => p.age)
//[20, 19]

【讨论】:

    【解决方案2】:

    reduce() 要求您从回调函数中返回累加器(因为累加器可能不是可变对象)。 push() 返回更新后数组的长度,所以第二次迭代尝试做(1).push(curr.age, []),这不起作用。

    逗号运算符在箭头函数中对此很有用。

    此外,没有理由将[] 推送到acc。

    const people = [ { name: 'siddiq', age: 20} , { name: 'anas', age: 19}]
    const arr = people.reduce((acc, curr) => (acc.push(curr.age), acc), []);
    
    console.log(arr);

    【讨论】:

      【解决方案3】:

      另一种选择是使用spread syntax 以确保您以更简洁和现代的方式在reduce 方法中返回一个数组。

      const people = [ { name: 'siddiq', age: 20} , { name: 'anas', age: 19}]
      const arr = people.reduce((acc, curr) => [...acc, curr.age], []);
      
      console.log(arr);

      【讨论】:

        猜你喜欢
        • 2022-10-12
        • 2021-03-13
        • 2016-03-12
        • 2013-11-14
        • 2020-06-07
        • 1970-01-01
        • 2020-03-26
        • 2021-07-17
        • 2016-06-10
        相关资源
        最近更新 更多