青训营笔记 | 手写JavaScript数组的方法

91 阅读1分钟

手写find和findindex

我们首先先创建一个index.js的文件在文件中定义一个数组,就像这样

let arr = ["1", "2", "3"];

let find = arr.find(function (item) {
  return item == "1";
});

console.log(find);

使用node index.js运行这段代码,我们可以看到输出的结果是
1
现在让我们来实现自己的find方法吧

let arr = ["1", "2", "3"];

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

const find = arr.myFind(function (item) {
  return item == "1";
});

console.log(find);

接下来是findindex方法的实现

let arr = ["1", "2", "3"];

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

const find = arr.myFindIndex(function (item) {
  return item == "1";
});

console.log(find);

手写reduce

我们首先先创建一个index.js的文件在文件中定义一个数组,就像这样

const arr = [1, 2, 3, 4, 5];

const res = arr.reduce(function (sum, item) {
  return sum + item;
});

console.log(res);

使用node index.js运行这段代码,我们可以看到输出的结果是
15
现在让我们来实现自己的reduce方法吧

const arr = [1, 2, 3, 4, 5];

Array.prototype.myReduce = function (fn, initValue) {
  for (let i = 0; i < this.length; i++) {
    initValue = fn(initValue, this[i], i, this);
  }
  return initValue;
};

const res = arr.myReduce(function (sum, item) {
  return sum + item;
}, 0);

console.log(res);

手写every

我们首先先创建一个index.js的文件在文件中定义一个数组,就像这样

const user = [
  { name: "李四", js: 89 },
  { name: "马六", js: 65 },
  { name: "张三", js: 78 },
];

const resust = user.every((user) => user.js >= 60);

console.log(resust);

使用node index.js运行这段代码,我们可以看到输出的结果是
true
现在让我们来实现自己的every方法吧

const user = [
  { name: "李四", js: 89 },
  { name: "马六", js: 65 },
  { name: "张三", js: 78 },
];

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

const resust = user.myEvery((user) => user.js >= 60);
console.log(resust);