美文网首页
自定义ES6提供的数组方法(reverse、reduce)

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

作者: jw_fc89 | 来源:发表于2021-11-14 19:01 被阅读0次

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

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;
    }
}

相关文章

网友评论

      本文标题:自定义ES6提供的数组方法(reverse、reduce)

      本文链接:https://www.haomeiwen.com/subject/xpdxtrtx.html