1.arr.some(function(){})
只要有满足条件的元素,结果就为true,如果都不满足,就为false,return布尔值。
不改变原数组。
实现原理:
Array.prototype.some = function (callback) { for (let i = 0; i < this.length; i++) { let isTrue = callback(this[i], i) if (isTrue) return true } return false }
2.arr.every(function(){})
只要有一个不满足条件的元素,结果就为false,如果都满足,就为true,return布尔值。
不改变原数组。
实现原理:
Array.prototype.every = function (callback) { for (let i = 0; i < this.length; i++) { let isTrue = callback(this[i], i) if (!isTrue) return false } return true }
3.arr.find(function(){})
返回的是第一个满足条件的元素,如果没有满足条件的元素,就返回undefined。
不改变原数组。
实现原理:
Array.prototype.find = function (callback) { for (let i = 0; i < this.length; i++) { let isTrue = callback(this[i], i) if (isTrue) return this[i] } }
4.arr.filter(function(){})
返回满足条件的新数组,不改变原数组。
实现原理:
Array.prototype.filter = function (callback) { let res = [] for (let i = 0; i < this.length; i++) { let isTrue = callback(this[i], i) if (isTrue) res.push(this[i]) } return res }
5.arr.forEach(function(){})
遍历数组中的每个元素,对数组的每个元素做运算。总是返回undefined,会改变原数组。
实现原理:
Array.prototype.forEach = function (callback) { for (let i = 0; i < this.length; i++) { callback(this[i], i) } }
6.arr.map(function(){})
不改变原数组,返回的是操作后的新数组。
实现原理:
Array.prototype.map = function (callback) { let res = [] for (let i = 0; i < this.length; i++) { let obj = callback(this[i], i) res.push(obj) } return res } let arr = [{ age: 20, name: "simba" }, { age: 30, name: "ace" }, { age: 40, name: "roger" }] console.log(arr.map(r => r.age)); console.log(arr.map(r => r.name)); console.log(arr.map((r, i) => ({ id: i + 1, age: r.age + "岁" })));