![](/img/trans.png)
[英]Can someone explain to me why this syntax using parentheses instead of curly brackets, adding comma and no more “return” in reduce method?
[英]Can someone explain why this reduce method return like this?
我有一個 object 數組,如下所示:
var voters = [
{name:'Bob' , age: 30, voted: true},
{name:'Jake' , age: 32, voted: true},
{name:'Kate' , age: 25, voted: false},
{name:'Sam' , age: 20, voted: false},
{name:'Phil' , age: 21, voted: true},
{name:'Ed' , age:55, voted:true},
{name:'Tami' , age: 54, voted:true},
{name: 'Mary', age: 31, voted: false},
{name: 'Becky', age: 43, voted: false},
{name: 'Joey', age: 41, voted: true},
{name: 'Jeff', age: 30, voted: true},
{name: 'Zack', age: 19, voted: false}
];
我用 reduce 來計算投票的人數:
function totalVotes(arr) {
return arr.reduce(function voteCount(acc,cur){
return acc+cur.voted;
},0)
}
function 返回正確答案,這讓我感到困惑。 它沒有任何條件來檢查那個人是否被投票,那么它如何返回正確的答案?
通過執行acc+cur.voted
您可以將 boolean cur.voted
隱式轉換為一個數字(false -> 0,true -> 1)。 因此,通過“加起來”這些布爾值,您將收到布爾true
的計數:
console.log( true + false, true + true );
Javascript 具有使用類型強制的動態類型系統。 當您有一個包含兩個變量的表達式時,其中一個是 integer 並且是 boolean 類型強制發生。 bool 值將被解釋為 1 或 0。在交互式 JS(例如 node、repl.it)中試試這個:
0 + true
它返回1
。
在您的減少回調 function 中,您從累加器acc
的初始值 0 開始。 然后將 boolean 值cur.voted
添加到它。 這將為帶有voted = true
的列表元素返回acc
acc + 1
,對於帶有voted = false
的列表元素返回 acc 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.