Javascript: Reduce function with ||
Javascript: Reduce function with ||
谁能解释一下下面的代码?inputWords应该是一个包含各种单词的数组,该函数应该返回一个包含单词在inputWords中出现次数的数组。
ie。var inputWords =['苹果','香蕉','苹果','榴莲','榴莲','榴莲']
console.log(countWords(inputWords))
// =>
// {
// Apple: 2,
// Banana: 1,
// Durian: 3
// }
我理解Reduce函数的作用,但是resultObj[word] = ++resultObj[word] || 1;在做什么?
Thanks so much:)
function countWords(inputWords) {
return inputWords.reduce(function(resultObj, word) {
resultObj[word] = ++resultObj[word] || 1;
return resultObj;
}, {});
}
module.exports = countWords;
代码尝试为一个键(可能还不存在)分配一个递增值,如果false ,则赋值1。
这称为短路求值。给定a = b || c
,如果b
为真,则c
不被求值,因此a
取b
的值。如果b
为false ,则计算c
并将其赋值给a
。在您的示例中,当键不存在时,++resultObj[word]
为false。
在我看来,我认为如果他们这样做的话,会更清楚地说明作者的意图:
if (word in resultObj) {
++resultObj[word];
}
else {
resultObj[word] = 1;
}
甚至:
resultObj[word] = word in resultObj ? resultObj[word] + 1 : 1;
将resultObj
中不存在的密钥"默认"为1
。
Javascript的||
实际上会在比较中返回第一个(最左边的)真值,所以对于一个不存在的值,通过预增运算符(如++resultObj['banana']
)添加一个,返回NaN
,这是假的,||
运算符将用1
替换它。
编辑:参见http://nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/
我会写:
resultObj[word] = (resultObj[word] || 0) + 1;
相关文章:
- Troubles with (function(){})()
- Javascript setTimeout function with JQuery
- Javascript get "this" class with onClick function
- onClientClick with JavaScript function and eval
- AngularJS Function with ng-if inside ng-repeat
- Javascript Autocomplete Function with Django
- JQuery fadeTo() Function with scrollTop()
- javascript function with jquery
- Function.prototype.bind with null 作为参数
- Lab.js 和 jQuery with $(window).load(function() 过早触发
- AJAX & Json get function with jQuery
- Javascript function arguments with "-"
- Having issue with click function for <tr>
- Javascript setTimeout function with 'this'
- PHP Function with jQuery AJAX?
- Jquery - Using a function with .click and 'this'
- form_for with onsubmit() jQuery function
- Knockoutjs为什么使用“with”?语句和“new function”;实现它的bindingProvider
- Lodash: _.forEach with function
- JS function with bug