一、filter
**语法**
array.filter(function(currentValue,index,arr), thisValue)
参数说明
currentValue: 必须。当前元素的值
index: 可选。当前元素的索引值
arr: 可选。当前元素属于的数组对象
thisValue: 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。\
如果省略了 thisValue ,"this" 的值为 undefined
返回值: 返回数组,包含了符合条件的所有元素。如果没有符合条件的元素则返回空数组。
手写实现
Array.prototype.myFilter = function (fn, thisValue) {
if (typeof fn !== 'function') {
throw new Error(`${fn} 不是一个函数`)
}
if ([null, undefined].includes(this)) {
throw new Error(`this 是null 或者 undefined`)
}
const arr = Object(this)
const filterArr = []
for (let i = 0; i < arr.length; i++) {
const res = fn.call(thisValue, arr[i], i, arr)
if (res) {
filterArr.push(arr[i])
}
}
return filterArr
}
二、some
**语法**
array.some(function(currentValue,index,arr),thisValue)
参数说明
currentValue: 必须。当前元素的值
index: 可选。当前元素的索引值
arr: 可选。当前元素属于的数组对象
thisValue: 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。\
如果省略了 thisValue ,"this" 的值为 undefined
返回值: 布尔值。如果数组中有元素满足条件返回 true,否则返回 false。
手写实现
Array.prototype.mySome = function (fn, thisValue) {
if (typeof fn !== 'function') {
throw new Error(`${fn} 不是一个函数`)
}
if ([null, undefined].includes(this)) {
throw new Error(`this 是null 或者 undefined`)
}
const arr = Object(this)
let flag = false
for (let i = 0; i < arr.length; i++) {
const res = fn.call(thisValue, arr[i], i, arr)
if (res) {
return true
}
}
return flag
}
三、every
**语法**
array.every(function(currentValue,index,arr), thisValue)
参数说明
currentValue: 必须。当前元素的值
index: 可选。当前元素的索引值
arr: 可选。当前元素属于的数组对象
thisValue: 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 undefined
返回值: 布尔值。如果所有元素都通过检测返回 true,否则返回 false。
手写实现
Array.prototype.myEvery = function (fn, thisValue) {
if (typeof fn !== 'function') {
throw new Error(`${fn} 不是一个函数`)
}
if ([null, undefined].includes(this)) {
throw new Error(`this 是null 或者 undefined`)
}
const arr = Object(this)
let flag = true
for (let i = 0; i < arr.length; i++) {
const res = fn.call(thisValue, arr[i], i, arr)
if (!res) {
return false
}
}
return flag
}
四、reduce
**语法**
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
定义和用法
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
**注意:** reduce() 对于空数组是不会执行回调函数的。
参数说明
total: 必需。初始值, 或者计算结束后的返回值。
currentValue: 必须。当前元素的值
currentIndex: 可选。当前元素的索引值
arr: 可选。当前元素属于的数组对象
initialValue: 可选。传递给函数的初始值
返回值: 返回计算结果
手写实现
Array.prototype.myReduce = function (fn, initialValue) {
if (typeof fn !== 'function') {
throw new Error(`${fn} 不是一个函数`)
}
if (!Array.isArray(this)) {
throw new Error(`this 不是数组`)
}
const arr = Object(this)
if (!arr.length) {
return
}
let accumulator = initialValue || arr[0]
let i = initialValue ? 0 : 1
for (; i < arr.length; i++) {
accumulator = fn(accumulator, arr[i], i, arr)
}
return accumulator
}