【问题标题】:What role does the parameter `{count}` play in the following `reduce` call? [duplicate]参数 `{count}` 在下面的 `reduce` 调用中起什么作用? [复制]
【发布时间】:2018-07-15 17:03:16
【问题描述】:

这是 JavaScript 的 sn-p。正在调用reduce 函数来计算出现次数,并将计数返回给变量totalreduce函数调用可以概括为reduce(array, someFunction, start){function body}

下面使用的reduce 的具体实例是reduce(array, (a,b) => a + b, 0) 的形式。在下面的sn-p中,{count}这个表达式是怎么用的,为什么用大括号{}括起来?在我看来它既不是函数体也不是对象。

let total = scripts.reduce((n, {count}) => n + count, 0);

if (total == 0) return "No scripts found";

【问题讨论】:

  • destructuring{count} 表示scripts 数组中的元素是具有count 属性的对象。 {count} 提取那些。 n + count 和初始值0 也暗示每个count 属性的值都是一个数字。
  • 这是一个来自 Eloquent Javascript 的例子。几个关键点: 1. 看函数countBy的定义,同页。它返回一个具有 name 和 count 属性的对象数组 (counts.push({name, count: 1})) 这里使用的脚本对象是由这个函数创建的。 2. 在对象数组上使用数组方法reduce() 时,必须指定传入对象中的哪个对象属性应用作reducer 函数的currentValue。作者使用了解构,但他们可以写成(n, x)=> n + x.count,而不是(n, {count}) => n + count

标签: javascript parameters


【解决方案1】:

它遍历一个对象数组,其中这些对象具有count 属性。它提取该属性并对这些值求和。

当你将 1、2 和 3 相加时,输出为 6。

const scripts = [
  { count: 1, something: 'else' },
  { count: 2, foo: 'bar' },
  { count: 3, baz: '23', arr: [1, 2, 3] }
];

let total = scripts.reduce((n, {count}) => n + count, 0);

console.log(total);

它被称为object destructuring,更简单的例子是。

const obj = { count: 3, foo: 'bar' };

const { count } = obj; // <- extracts value from count property

console.log(count);

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多