鍍金池/ 問答/HTML/ 關(guān)于reduce()的問題

關(guān)于reduce()的問題

function getSum(total, num) {
    return total + Math.round(num);
}
function myFunction(numbers) {
    return numbers.reduce(getSum, 0);// 24
    return numbers.reduce(getSum);// 23.5 為什么改變了傳遞給函數(shù)的初始值,得出的結(jié)果不一樣?
}

myFunction([15.5, 2.3, 1.1, 4.7]);
var numbers = [65, 44, 12, 4];

function getSum(total, num) {
    return total + num;
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);// 125
    document.getElementById("demo").innerHTML = numbers.reduce(getSum);// 125 為什么這里沒有改變
}
回答
編輯回答
殘淚

你若不指定默認(rèn)值,那么total參數(shù)第一輪計(jì)算中就是第一個(gè)數(shù)。
[15.5, 2.3, 1.1, 4.7]這里相當(dāng)于 15.5是第一個(gè)total(沒參與四舍五入),然后不斷加后面四舍五入的數(shù),結(jié)果就是23.5; 如果設(shè)置了total默認(rèn)值0,它把后面所有的數(shù)都四舍五入后相加了,故是24.

第二個(gè)問題不用解答了,你肯定也明白,因?yàn)槔锩娑际钦麛?shù),不會(huì)出現(xiàn)差異。

2017年3月14日 05:47
編輯回答
兔寶寶

首先解釋一下reduce函數(shù)的參數(shù):

callback

執(zhí)行數(shù)組中每個(gè)值的函數(shù),包含四個(gè)參數(shù):
  • accumulator
    累加器累加回調(diào)的返回值; 它是上一次調(diào)用回調(diào)時(shí)返回的累積值,或initialValue(如下所示)。
  • currentValue
    數(shù)組中正在處理的元素。
  • currentIndex可選
    數(shù)組中正在處理的當(dāng)前元素的索引。 如果提供了initialValue,則索引號(hào)為0,否則為索引為1。
  • array可選
    調(diào)用reduce的數(shù)組

initialValue可選

用作第一個(gè)調(diào)用 callback的第一個(gè)參數(shù)的值。 如果沒有提供初始值,則將使用數(shù)組中的第一個(gè)元素。 在沒有初始值的空數(shù)組上調(diào)用 reduce 將報(bào)錯(cuò)

返回值

函數(shù)累計(jì)處理的結(jié)果

文檔還有一個(gè)polyfill的實(shí)現(xiàn),看一下實(shí)現(xiàn)就明白了。

if (!Array.prototype.reduce) {
  Object.defineProperty(Array.prototype, 'reduce', {
    value: function(callback /*, initialValue*/) {
      if (this === null) {
        throw new TypeError( 'Array.prototype.reduce ' + 
          'called on null or undefined' );
      }
      if (typeof callback !== 'function') {
        throw new TypeError( callback +
          ' is not a function');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0; 

      // Steps 3, 4, 5, 6, 7      
      var k = 0; 
      var value;

      if (arguments.length >= 2) {
        value = arguments[1];
      } else {
        while (k < len && !(k in o)) {
          k++; 
        }

        // 3. If len is 0 and initialValue is not present,
        //    throw a TypeError exception.
        if (k >= len) {
          throw new TypeError( 'Reduce of empty array ' +
            'with no initial value' );
        }
        value = o[k++];
      }

      // 8. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kPresent be ? HasProperty(O, Pk).
        // c. If kPresent is true, then
        //    i.  Let kValue be ? Get(O, Pk).
        //    ii. Let accumulator be ? Call(
        //          callbackfn, undefined,
        //          ? accumulator, kValue, k, O ?).
        if (k in o) {
          value = callback(value, o[k], k, o);
        }

        // d. Increase k by 1.      
        k++;
      }

      // 9. Return accumulator.
      return value;
    }
  });
}
2017年9月3日 19:05