forEach
注意:
forEach 没有返回值,forEach循环无法停止(在其中加break无效),不改变原数组。
const arr = [2,4,6,8,10]
arr.forEach((item, index) => {
console.log(item, index)
})
2, 0
4, 1
6, 2
8, 3
10, 4
- 底层实现:
Array.prototype.forEach = function(fn) {
if (typeof fn !== 'function') {
throw new TypeError(`${fn} must be an function`)
}
for (let i=0; i<this.length; i++) {
fn(this[i], i)
}
}
filter
作用:
筛选数据,筛选出数组中所有满足条件的元素项目,得到一个新数组,循环结束,返回新数组,不改变原数组。
const todos = [2,4,6,7,8]
const arr1 = todos.filter(item => item > 5)
console.log(arr1) // [6,7,8]
- 底层实现:
Array.ptototype.filter = function(fn) {
if (typeof fn !== 'function') {
throw new TypeError(`${fn} must be an function`)
}
const newArr = []
for (let i=0; i<this.length; i++) {
fn(this[i]) && newArr.push(this[i])
}
return newArr
}
find
作用:
遍历数组,找到符合条件的元素,不改变原数组。注意:
找到第一个满足条件的元素,就返回,不再往后遍历。
const todos = [2,4,6,7,8]
const arr1 = todos.find(item => item > 5)
console.log(arr1) // 6
- 底层实现
Array.prototype.find = function(fn) {
if (typeof fn !== 'function') {
throw new TypeError(`${fn} must be an function`)
}
for (let i=0; i<this.length; i++) {
if (fn(this[i])) {
return this[i]
}
}
}
map
作用:
根据源数据映射出一个新的数组(个数不变,但里面的元素内容可以定制),不改变原数组。
const todos = [
{ id: 1, name: 'zhangsan', age: 10 },
{ id: 2, name: 'lisi', age: 15 }
]
const arr = todos.map((item) => {
return item.name
})
console.log(arr) // ['zhangsan', 'lisi']
- 底层实现
Array.prototype.map = function(fn) {
if (typeof fn !== 'function') {
throw new TypeError(`${fn} must be an function`)
}
let newArr = []
for (let i=0; i<this.length; i++) {
newArr.push(this[i])
}
return newArr
}
some
作用:
判断数组中是否有指定条件的元素,不改变原数组。注意:
返回一个布尔值
const arr = [2,4,6,8,10]
const flag = arr.some(item => item >5)
console.log(flag) // true
- 底层实现
Array.prototype.some = function(fn) {
if (typeof fn !== 'function') {
throw new TypeError(`${fn} must be an function`)
}
for (let i=0; i<this.length; i++) {
if (fn(this[i])) {
return true
}
}
return false
}
every
作用:
判断数组中所有元素是否满足指定条件(和some正好相反),不改变原数组。注意:
- 返回值为布尔值
- 当空数组遍历时,返回的就是true,因此当空数组遍历时需要做特殊处理
// 空数组的处理
const temArr = []
const flag = [].every(item => item.flag) 需严谨修改为
const flag = temArr.length ? temArr.every(item => item.flag) : false
const arr = [2,4,6,8]
const flag = arr.every(item => item > 5)
console.log(flag) // false
- 底层实现
Array.prototype.every = function(fn) {
if (typeof fn !== 'function') {
throw new TypeError(`${fn} must be an function`)
}
for (let i=0; i<this.length; i++) {
if (!fn(this[i])) {
return false
}
}
return true
}
reduce
作用:
数组中的元素累加起来求得一个最终结果,不改变原数组。注意:
- 第1个参数:累计器
- 第2个参数:当前值
- 第3个参数:当前索引
- 第4个参数:源数组
prev 是上一次的计算结果,第1次的值是你指定的初始值,之后都是上一次的结果
const todos = [2,4,6,8,10]
const result = arr.reduce(function (prev, item, index, origin) {
return prev + item
}, 0)
console.log(result) // 20
- 底层实现
Array.prototype.reduce = function(reducer, initVal) {
for (let i=0; i<this.length; i++) {
initVal = reducer(initVal, this[i], i, this)
}
return initVal
}