forEach()
forEach没有返回值。
是一个普通的for循环,写法上比for循环简单,适用于普通的循环
接收三个参数:每个数组的元素,下标index,自身
let a1 = ['hello', 'world']
let b1 = a1.forEach((item, i, arr) => {
console.log(item, i, arr)
})
console.log(b1) // undefined
map()
map返回一个新数组。
在使用过程中当需要返回一个新的数组时,建议优先使用map,而不是forEach
let a2 = [1, 2, 3]
let b2 = a2.map(v => {
return v * 2
})
console.log(a) // [1, 2, 3]
console.log(b) // [2, 4, 6]
filter()
filter返回一个新数组。
返回符合指定要求的数组
let a3 = [
{
title: '标题1',
show: true
},
{
title:'标题2',
show: false
},
{
title:'标题3',
show: true
}
]
let b3 = a3.filter(item => {
return item.show // 返回show为true的数据
})
console.log(b3)
some()
some返回一个Boolean类型数据。
当数组中其中一个元素满足指定要求即返回true,否则返回false
let a4 = ['yellow', 'red', 'blue']
let b4 = a4.some(v => {
return v === 'red'
})
console.log(b4) // true
every()
every返回一个Boolean类型的数据。
当数组中所有的元素都满足指定要求即返回true,否则返回false
let a5 = [2, 4, 6, 8]
let b5 = a5.every(v => {
return v % 2 === 0 // 判断数组中的元素是不是都是偶数
})
console.log(b5) // true
reduce()
reduce可用于计算数组的和
let a6 = [1, 2, 3, 4, 5, 6 ,7, 8, 9, 10]
/**
* preTotal:之前值的和
* currentValue: 当前值
*/
let b6 = a6.reduce((preTotal, currentValue) => {
console.log(currentValue) /*1, 2 ... 7, 8, 9*/
return preTotal + currentValue
})
console.log(b6) // 55
reduceRight()
执行顺序与reduce相反
let a6 = [1, 2, 3, 4, 5, 6 ,7, 8, 9, 10]
/**
* preTotal:之前值的和
* currentValue: 当前值
*/
let b7 = a6.reduceRight((preTotal, currentValue) => {
console.log(currentValue) /*9, 8, 7 ... 2, 1**/
return preTotal + currentValue
})
console.log(b7) //55
find()
find返回通过指定条件(函数内判断)的数组的第一个元素的值。
let a8 = [
{
name: 'Tom',
age: 18
},
{
name: 'Anny',
age: 15
},
{
name: 'Kobe',
age: 22
},
]
let b8 = a8.find((item) => {
return item.age > 15
})
console.log(b8) // {name: 'Tom', age: 18}
findIndex()
find方法返回通过指定条件(函数内判断)的数组的第一个元素的值。
let a9 = ['webpack', 'node', 'vue']
let b9 = a9.findIndex(v => {
return v === 'node'
})
console.log(b9) // 1
for of
let arr = ['apple', 'banana', 'orange']
for (let val of arr) {
console.log(val) // 'apple', 'banana', 'orange'
}
for (let index of arr.keys()) {
console.log(index) // 0 1 2
}
for (let [index, val] of arr.entries()) {
console.log(index, val) // 0 "apple" 1 "banana" 2 "orange"
}
Mxue note