有人能解释一下reduce方法在这个函数式JavaScript挑战中是如何工作的吗?
根据reduce的文件 reduce()方法对累加器和每个累加器应用一个函数 数组的值(从左到右),以将其减少为单个 价值观 这就是任务: 给定一个字符串数组,使用Array#reduce创建一个 包含数组中每个字符串出现的次数。返回 直接创建对象(不需要console.log) 例子 这就是解决方案:有人能解释一下reduce方法在这个函数式JavaScript挑战中是如何工作的吗?,javascript,Javascript,根据reduce的文件 reduce()方法对累加器和每个累加器应用一个函数 数组的值(从左到右),以将其减少为单个 价值观 这就是任务: 给定一个字符串数组,使用Array#reduce创建一个 包含数组中每个字符串出现的次数。返回 直接创建对象(不需要console.log) 例子 这就是解决方案: function countWords(inputWords){ return inputWords.reduce(function(wordCount, currentValue){
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;
数组中的每个标记不是一个“字符串”吗?对象是如何创建的?我知道迭代器是如何实现的,但是有人能解释一下发生了什么吗?reduce函数有两个参数:
然后,回调函数返回的任何值都会传递到
wordCount
位置的回调函数
在这个例子中。。。您的currentValue
是用对象文本(reduce
函数的第二个参数)初始化的
在那之后。。。它每次都返回更新的对象文本,从而构建其状态
查看正在构建的状态的一个好方法是在回调函数的末尾放置一个console.log
签出(并查看调试器控制台)。函数的每次调用都会传递最后一个结果、
字数和数组的当前元素。reduce的第二个参数传递wordCount
的初始值,在本例中,该值为空对象文本
Reduce将为每个元素调用函数。每次调用时,wordCount
都会更新并返回,并在下次调用时作为wordCount
传递。在函数中更新wordCount
不会影响下次调用时的wordCount
,返回的是下次调用时设置为wordCount
的内容
下面是每个过程的外观(值和变量从示例中缩短以适合):
返回的值是{'Apple':2,'Banana':1,'Durian':3}
传递给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;
因此,如果您要查看函数的第一次和第三次迭代,它们将如下所示:
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;
该对象由两个字符的对象文本{}
创建,它作为reduce
操作的初始累加器值提供。每次迭代,累加器对象要么被赋予一个由考虑中的字符串命名的新属性(并被赋予一个初始值1),要么现有属性增加一个。您是否不清楚该解释的任何特定部分?请阅读上的MDN文档。请注意,此代码不太擅长计算“构造函数”一词<代码>:)
(注意:这与您的问题无关,但这是一个由过于一般的测试if(!wordCount[currentValue])
引起的错误,该测试将继承的属性构造函数
计算为已看到的单词。)},{})
相当于},new Object())
“然后,从回调函数返回的任何值都会传递到位于currentValue
位置的回调函数。”应该是wordCount
,而不是currentValue
currentValue
是inputWords
中的当前数组元素。