手写map,filter,some,every方法
map方法
map用于遍历数组
//原型对象中的this指向实例出来的对象
[].__proto__.myMap = function (callback) {
for (let index = 0; index < this.length; index++) {
callback(this[index], index, this)
}
}
const arr = [1,3,5,7]
const res = arr.myMap((item, index) => {
console.log(item, index);
})
filter方法
filter主要用于筛选出满足条件的元素,返回一个新数组
[].__proto__.myFliter = function (callback) {
const newArr = []
for (let index = 0; index < this.length; index++) {
//返回值为真,就说明满足条件,就添加到新数组中
const flag = callback(this[index], index)
if (flag) {
newArr.push(index)
}
}
return newArr
}
const arr = [1, 2, 3, 4, 5, 6, 7]
const res = arr.filter(item => item > 5)
console.log(res);
some方法
some用来判断数组中只要有一个元素满足就返回为true,否则返回false
[].__proto__.mySome = function (callback) {
for (let index = 0; index < this.length; index++) {
//如果返回值为真,就说明满足条件,就返回true
if (callback(this[index], index, this)) return true
}
return fasle
}
const arr = [1, 2, 3]
const res = arr.some(item => item % 2 === 0)
console.log(res);
every方法
every遍历数组,所有元素都满足条件才返回true,否则返回false
[].__proto__.myEvery = function (callback) {
let falg = null
for (let index = 0; index < this.length; index++) {
flag = callback(this[index])
//只要有一个返回值为假,就返回false,
if (!flag) return false
}
//否则返回true
return true
}
const arr = [2, 4, 6, 1]
const res = arr.myEvery(item => item % 2 === 0)
console.log(res);