yanyue404 / blog

Just blog and not just blog.
https://yanyue404.github.io/blog/
Other
88 stars 13 forks source link

JavaScript 数组 API #131

Open yanyue404 opened 4 years ago

yanyue404 commented 4 years ago

数组方法分类

IE8 之前可以用的数组方法

// 删除(删除索引开始值为3,数量为一个的元素)
const months = ['Jan', 'March', 'April', 'June'];
months.splice(3, 1);
console.log(months);
// 输出: Array ['Jan', 'March', 'April']

// 增加 (在索引值为1处插入)
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);
// 输出: Array ["Jan", "Feb", "March", "April", "June"]

// 替换 (在索引值为4处替换一个元素)
months.splice(4, 1, 'May');
console.log(months);
// 输出: Array ["Jan", "Feb", "March", "April", "May"]

es5 新加的数组方法

es2015(es6)新加的数组方法

es2016 新加的数组方法

es2018 新加的数组方法

数组 API 模拟实现

forEach

Array.prototype.y_forEach = function(fn) {
  for (let i = 0; i < this.length; i++) {
    if (i in this) {
      fn.call(undefined, this[i], i, this);
    }
  }
};
var arr = [12, 5, 8, 130, 44];
arr.y_forEach((v, i, arr) => {
  console.log(v, i, arr);
});

map

Array.prototype.y_map = function(fn) {
  let result = [];
  for (let i = 0; i < this.length; i++) {
    if (i in this) {
      result[i] = fn.call(undefined, this[i], i, this);
    }
  }
  return result;
};

var arr = [12, 5, 8, 130, 44];
var newArr = arr.y_map(v => v * 2);
console.log(newArr);

filter

Array.prototype.y_filter = function(fn) {
  let result = [];
  for (let i = 0; i < this.length; i++) {
    if (i in this) {
      if (fn.call(undefined, this[i], i, this)) {
        result.push(this[i]);
      }
    }
  }
  return result;
};

var arr = [12, 5, 8, 130, 44];
var filtered = arr.y_filter((v, i, arr) => {
  console.log(v, i, arr);
  return v > 10;
});

console.log('filtered', filtered); // => [12, 130, 44]

reduce

var arr = [1, 2, 3, 4];
Array.prototype.y_reduce = function(fn, init) {
  let result = init || 0; // 初始累计
  for (let i = 0; i < this.length; i++) {
    if (i in this) {
      // result 累计器 结果
      result = fn.call(undefined, result, this[i], i, this);
    }
  }
  return result;
};
console.log(
  arr.y_reduce((accumulator, currentValue, index, arr) => {
    console.log(
      '累计结算结果:' + accumulator,
      '当前值:' + currentValue,
      index,
      arr,
    );

    return accumulator * currentValue;
  }, 1),
);

参考链接