一、遍历数组
1.forEach() 操作数组的每一项
let users = [{name:'n1',age:16},{name:'n2',age:17},{name:'n3',age:18},
{name:'n4',age:19},{name:'n5',age:20},]
users.forEach((item)=>{
console.log(item.name);
}) //n1 n2 n3 n4 n5
2.map() 操作数组的每一项并返回一些内容
有返回值
let users = [{name:'n1',age:16},{name:'n2',age:17},{name:'n3',age:18},
{name:'n4',age:19},{name:'n5',age:20},]
let res = users.map((item)=>{
if(item.age>18) return item.age
})
console.log(res) //[undefined,undefined,undefined,19,20]
3.filter 过滤器
留下符合条件的元素
let users = [{name:'n1',age:16},{name:'n2',age:17},{name:'n3',age:18},
{name:'n4',age:19},{name:'n5',age:20},]
let res = users.filter((item)=>{
return item.age>18
})
console.log(res) //[{name:'n4',age:19},{name:'n5',age:20}]
二、查找
1.find 查找符合条件的第一个元素
let users = [{name:'n1',age:16},{name:'n2',age:17},{name:'n3',age:18},
{name:'n4',age:19},{name:'n5',age:20},]
let res = users.find((item)=>{
return item.age>18
})
console.log(res) //[{name:'n4',age:19}]
2.findIndex 查找符合条件的第一个元素的下标
let users = [{name:'n1',age:16},{name:'n2',age:17},{name:'n3',age:18},
{name:'n4',age:19},{name:'n5',age:20},]
let res = users.findIndex((item)=>{
return item.age>18
})
console.log(res) //3
三、判断 返回布尔值
1.some 有真则真
let users = [{name:'n1',age:16},{name:'n2',age:17},{name:'n3',age:18},
{name:'n4',age:19},{name:'n5',age:20},]
let res = users.some((item)=>{
return item.age>18
})
console.log(res) //true
2.every 有假则假
let users = [{name:'n1',age:16},{name:'n2',age:17},{name:'n3',age:18},
{name:'n4',age:19},{name:'n5',age:20},]
let res = users.every((item)=>{
return item.age>18
})
console.log(res) //false
四、特殊
1.reduce 常用作累加
用法
array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
callback
: 这是一个接受四个参数的函数,每个参数如下:accumulator
: 累加器的当前值,它可以是任何类型的值,初始值为initialValue
。currentValue
: 当前数组元素的值。currentIndex
: 当前元素的索引。array
: 调用reduce
的数组。
initialValue
: 这是累加器的初始值。如果未提供initialValue
,则将使用数组的第一个元素作为初始值,并且数组的第一个元素将不会被包含在遍历中。
实例
1.累加
let nums = [1,2,3,4,5]
let res = nums.reduce((accumulator,currentValue)=>{
return accumulator+currentValue
})
console.log(res) //15
2. 找到数组中的最大值
const numbers = [1, 2, 3, 4, 5];
const max = numbers.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue), -Infinity);
console.log(max); // 输出: 5
2.entries 返回一个迭代器,遍历这个数组,并为每个元素返回一个包含索引和值的数组
for (const [i, char] of array.entries()) {
if (array[char] === 1) {
return i;
}
}