Rumah  >  Soal Jawab  >  teks badan

javascript - js怎么实现Array的reduce函数?

思维不行,求指点?

PHPzPHPz2727 hari yang lalu425

membalas semua(2)saya akan balas

  • PHP中文网

    PHP中文网2017-04-11 12:48:38

    if (!Array.prototype.reduce) {
      Array.prototype.reduce = function(callback /*, initialValue*/) {
        'use strict';
        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');
        }
        var t = Object(this), len = t.length >>> 0, k = 0, value;
        if (arguments.length == 2) {
          value = arguments[1];
        } else {
          while (k < len && !(k in t)) {
            k++; 
          }
          if (k >= len) {
            throw new TypeError('Reduce of empty array with no initial value');
          }
          value = t[k++];
        }
        for (; k < len; k++) {
          if (k in t) {
            value = callback(value, t[k], k, t);
          }
        }
        return value;
      };
    }

    来源

    balas
    0
  • 黄舟

    黄舟2017-04-11 12:48:38

    遍历叠加呀。。。

    balas
    0
  • Batalbalas