[英]Can someone explain how the reduce method is working in this Functional JavaScript challenge?
根据 reduce.. 的文档
reduce() 方法对累加器和数组的每个值(从左到右)应用 function 以将其减少为单个值。
这是任务:
给定一个字符串数组,使用 Array#reduce 创建一个 object,其中包含每个字符串在数组中出现的次数。 直接返回object(不需要console.log)。
例子
var inputWords = ['Apple', 'Banana', 'Apple', 'Durian', 'Durian', 'Durian']
console.log(countWords(inputWords))
// =>
// {
// Apple: 2,
// Banana: 1,
// Durian: 3
// }
这是解决方案:
function countWords(inputWords){
return inputWords.reduce(function(wordCount, currentValue){
if (!wordCount[currentValue]){
wordCount[currentValue] = 1;
} else {
wordCount[currentValue] = wordCount[currentValue] + 1;
}
return wordCount;
},{});
}
module.exports = countWords;
数组中的每个索引不是一个“字符串”吗? object 是如何创建的? 我知道迭代器是如何实现的,但是有人可以解释发生了什么吗?
函数的每次调用都会传递最后的结果wordCount
和数组的当前元素。 reduce的第二个参数传递wordCount
的初始值,在这种情况下,该值是一个空的对象常量。
Reduce将为每个元素调用函数。 对于每个呼叫, wordCount
都会更新并返回,并在下一个呼叫中作为wordCount
传递。 在函数中更新wordCount
不会在下次调用时影响wordCount
,返回的值将是在下次调用时设置为wordCount
的值 。
每次通过时的外观如下(将值和变量从示例中缩短为适合):
index | curVal | wordCount | (returned)
----------------------------------------------------------------------------
0 | 'App' | { } | {'App':1}
1 | 'Ban' | { 'App': 1 } | {'App':1,'Ban':1}
2 | 'App' | { 'App': 1, 'Ban': 1 } | {'App':2,'Ban':1}
3 | 'Dur' | { 'App': 2, 'Ban': 1 } | {'App':2,'Ban':1,'Dur':1 }
4 | 'Dur' | { 'App': 2, 'Ban': 1, 'Dur': 1 } | {'App':2,'Ban':1,'Dur':2 }
5 | 'Dur' | { 'App': 2, 'Ban': 1, 'Dur': 2 } | {'App':2,'Ban':1,'Dur':3 }
返回的值为{ 'Apple': 2, 'Banana': 1, 'Durian': 3 }
reduce函数有两个参数:
从回调函数返回的任何值都将传递到wordCount
位置的回调函数中。
在此示例中,... currentValue
使用对象文字( reduce
函数的第二个参数)初始化。
之后,它每次都会返回更新的对象文字,从而建立其状态。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
查看正在建立状态的一个好方法是将console.log放在回调函数的末尾。
function countWords(arr) {
const yourObject = new Object();
let value = inputWords.reduce((a,val,index) => {
if(index==1){
yourObject[a]=1;
}
if (val in yourObject){
yourObject[val]=++yourObject[val];
}else{
yourObject[val]=1;
}
});
return yourObject;
传递给reduce的第二个参数是“ initialValue”,而您传递的是{}(空对象的实例)。 在每次调用函数时,“ wordCount”将是此对象。 在JavaScript中,您可以使用括号/字符串表示法引用对象的属性,如下所示:
someObject["someProperty"] = 2;
// ...is the same as
someObject.someProperty = 2;
因此,如果您要看一下函数的第一次和第三次迭代,它们将看起来像这样:
if (!wordCount["Apple"]){
// On first iteration, wordCount.Apple will be undefined, so set to 1
wordCount["Apple"] = 1;
// Object is now { Apple: 1 }
} else {
// On 3rd iteration, wordCount.Apple will already be 1, so we'll increment to 2
wordCount["Apple"] = wordCount["Apple"] + 1;
// Object is now { Apple: 2, Banana: 1 }
}
return wordCount;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.