[英]Reduce in javascript with initial value
我正在嘗試將數組減少為其偶數值的總和。 我一直在查看 MDN 的文檔 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
這表示如果提供了初始值,那么它不會跳過第 0 個索引,實際上它將從索引 0 開始。我的問題是 reduce 從索引 1 開始。因此,我的結果不正確。 我確定我閱讀文件不正確或誤解了它。 這是我指的注釋-“注意:如果沒有提供initialValue,reduce()將從索引1開始執行回調function,跳過第一個索引。如果提供了initialValue,它將從索引0開始。”
這是我的代碼。
var array = [1,2,3,4,6,100];
var initialValue = 0;
var value = array.reduce(function(accumulator, currentValue, currentIndex, array, initialValue) {
//console.log(accumulator);
if( currentValue % 2 === 0) {
accumulator += currentValue;
//return accumulator;
}
return accumulator;
});
console.log(value);
顯然,我看到的結果是 113 而不是 112。我猜,這是因為 accumulator 已經有一個值 1。因此,它最初是加 1。
如果你再看文檔,你會發現callbackFn
最多只取4個變量,而且initialValue
必須在第二個參數上
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
^ ^
這是按預期返回112
的小修復版本
var array = [1,2,3,4,6,100]; var initialValue = 0; var value = array.reduce(function(accumulator, currentValue, currentIndex, array) { //console.log(accumulator); if( currentValue % 2 === 0) { accumulator += currentValue; //return accumulator; } return accumulator; }, initialValue); console.log(value);
這是 MDN 提供的使用初始值的語法:
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
return accumulator + currentValue}, 10)
此示例中的初始值為 10,它應作為第二個參數傳遞給 reduce function。
您沒有將初始值參數傳遞給 reduce function。
就像@hgb123解釋的那樣,它是第二個參數。
此外,如果您不需要它們,則不需要傳遞所有參數。 讓你的函數盡可能簡單,這樣它們會更容易閱讀:
var array = [1,2,3,4,6,100];
var value = array.reduce(function(accumulator, currentValue) {
//console.log(accumulator);
if( currentValue % 2 === 0) {
accumulator += currentValue;
//return accumulator;
}
return accumulator;
}, 0);
console.log(value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.