自定义ES6提供的数组方法(reverse、reduce)

2021-11-14  本文已影响0人  jw_fc89

接着上一次发布的文章,接下来我们继续看看数组内别的方法是怎么实现的。

reverse(数组反转顺序)

Array.prototype.reverse = function () {
       let temp = [];
       for (let index = 0; index < this.length; index++) {
          const element = this[index];
          temp.unshift(element);
        }
        return temp;
   }
// 或者
Array.prototype.reverse = function () {
     let temp = [];
     for (let index = this.length - 1; index >= 0; index--) {
           const element = this[index];
           temp.push(element)
       }
    return temp;
  }
var arr = [1, 2, 3];
arr.reverse();

reduce(计算数组元素相加后的总和)

Array.prototype.reduce = function (callback, initialValue) {
    if (callback && typeof (callback) === "function") {
        let total = typeof (this[0]) === "string" ? "" : 0;
        for (let index = 0; index < this.length; index++) {
            const currentValue = this[index];
            if (index === 0) {
                total = callback(initialValue, currentValue, index, this);
            } else {
                total = callback(total, currentValue, index, this);
            }
        }
        return total;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读