这里给大家分享下我搜索到的几个ES6常用数组方法及模拟实现,废话不多说,上代码

Array.from

可以将一个类数组转换成数组

在出现Array.from这个方法之前,我们转换类数组的方法:

Array.prototype.slice.call(arguments)

使用Array.form

Array.from(arguments, item => {
  return item;
})

Array.prototype.findIndex

查找数组中对应的索引
let arr = [1,2,3,4,5];
const index = arr.findIndex(item => item === 1); // output:0

模拟实现findIndex

  Array.prototype.findIndex = function(callback){
    for(let i = 0; i<this.length; i++){
      if( callback(this[i]) ){
         return i;
      }
    }
    return -1;
  }

Array.prototype.find

查找数组中的某个元素

  let arr = [1,2,3,4];
  arr.find(item => item > 2); // output: 3

模拟实现find

  Array.prototype.find = function(callback) {
    for(let i = 0; i < this.length; i++){
      let flag = callback(this[i]);
      if(flag){
        return this[i]
      }
    }
    return undefined;
  } 

Array.prototype.map

map方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果

  const arr = [1,2,3];
  arr.map(item => item * 2) // output: [2,4,6]

模拟实现map

  Array.prototype.map = function(callback) {
    let newArr = [];
    for(let i = 0; i < this.length; i++){
      let result = callback(this[i]);
      newArr.push(result);
    }
    return newArr;
  }

注意这里提个小只是,通过map的模拟实现应该可以大致明白为什么map和foreach不能跳出循环

Array.prototype.reduce

方法对累计器和数组中的每个元素(从左到右)应用一个函数,将其简化为单个值

const arr = [2,3,4];
  // output: 9
  const sum = arr.reduce((sum, item) => {
    sum += item;
    return sum;
  },0);

模拟实现reduce

  Array.prototype.reduce = function(callback, initialValue){
    let sum = initialValue || this[0];
    if(!sum){
      return;
    }
    for(let i = 0; i < this.length; i++){
      sum = callback(sum, this[i], i , this);
    }
    return sum;
  }

Array.prototype.some

数组中的元素,有一个满足条件,则返回true

var arr = [1, 2, 3];

arr.some(item => item > 2); // output: true

模拟实现some

Array.prototype.some = function(callback) {
  for(let i = 0; i < this.length; i++) {
    if(callback(this[i])){
      return true;
    }
  }
  return false;
}

Array.prototype.every

数组中的所有元素都满足条件,则返回true

var arr = [1, 2, 3];

arr.every(item => item > 2); // output: false

模拟实现every

Array.prototype.every = function(callback){
  for(let i = 0; i < this.length; i++){
    if(!callback(this[i])){
      return false;
    }
  }
  return true;
}

Array.prototype.filter

filter方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素

  let arr = [1,2,3];
  arr.filter(item => item > 2); // output: [3]

模拟实现filter

  Array.prototype.filter = function(callback) {
    let newArr = [];
    for(let i = 0; i < this.length; i++){
      let flag = callback(this[i]);
      if(flag){
        newArr.push(this[i])
      }
    }
    return newArr;
  }

如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/smileZAZ/p/15812200.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!