繁体   English   中英

从MDN还原示例的说明

[英]Explanation of reduce example from mdn

有人可以详细说明一下此代码段

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) { 
    if (name in allNames) {
        allNames[name]++;
    } else {
        allNames[name] = 1;
    }
    return allNames;
}, {}); 

请说明回调函数如何获取数组名称并给出答案

countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

更清楚地说,这是从功能到过程的相同代码

const names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

const countedNames = {};
for (let i = 0; i < names.length; i++) {
  let name = names[i];
  // if exists increment, else set to 1
  if (countedNames[name] != null) {
    countedNames[name]++;
  } else {
    countedNames[name] = 1;
  }
}

console.log(countedNames);

在reduce {}是初始值,然后数组中的每个元素都通过reduce函数运行以修改最终值。

这定义并排列了5个元素

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

让我们分别定义函数以便于解释

此函数接受两个参数(allNames, name) 该函数返回的allNames在每次迭代时都会添加到allNames中。

var myFunc = function (allNames, name) {

如果allNames已经包含name ,则将其值递增

   if (name in allNames) {
        allNames[name]++;
    }

否则,将name添加为键并将其值设置为1

    else {
        allNames[name] = 1;
    }

从此函数返回allNames ,因此reduce可以将其作为allNames传递allNames下一个迭代

   return allNames;
}

这会将countedNames .reduce()的结果分配给countedNames并且{}是初始值

var countedNames = names.reduce(myFunc, {}); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM