数组遍历方法汇总:
forEach:
- 单纯的遍历数组,数组的值依次会进入到回调函数中
- 没有返回值
//案例代码
const arr = ["海绵宝宝", "派大星", "章鱼哥"];
arr.forEach((item) => {
console.log(item);
});
map
- 映射数组,有点类似于浅拷贝的感觉
- 返回和原数组长度一样的数组,返回的数据相当于是新创建,与以前的地址是不同的
- 数组的值依次进入回调函数中,当次回调函数的返回值就是对应的映射数组位置的值
var baseArr1 = ["a", "b", "c", "d"];
var mapResult = baseArr1.map(function (item) {
return item + "1";
});
console.log(mapResult);
执行逻辑是遍历数组中的每一个值,每次遍历一个数组中一个数据项,都会执行里面的回调函数返回一个要存到新数组的值
some
- 遍历数组的每一个值,数组的值会依次进入回调函数中执行
- 如果某个回调函数返回true,则停止遍历,some方法直接返回true
- 一真即真
数据源,一个数组对象
var baseArr2 = [
{
name: "xiaoyang",
age: 18,
},
{
name: "xiaonie",
age: 21,
},
{
name: "yangnie",
age: 13,
},
{
name: "nienie",
age: 22,
},
];
var someResult = baseArr2.some(function (item, index) {
console.log("some的index", index);
//打印的结果是:0,1,2
return item.age < 18;
});
console.log(someResult,"返回的结果");
//打印的结果是true
item:是遍历中数组中的每一个对象,index:是数据项的下标,回调函数返回一个布尔值 当执行到index=3的时候,发现第一个满足条件的结果,就会返回true,就不会再往下执行了
every
- 遍历数组的每一个值,数组的值会依次进入回调函数中执行
- 如果所有的值进入回调函数都返回true,则every方法返回true,否则返回false,并停止遍历
- 一假即假
var everyResult = baseArr2.every(function (item, index) {
consle.log("idnex",index)
return item.age > 18 })
console.log("everyResult", everyResult);
//打印结果是: false
当遍历到第一个不满足条件的false的时候就会停止执行,返回false
filter
过滤,返回满足过滤条件的数组
根据回调函数中的条件,返回所有符合条件(回调函数返回true) 的值组成的数组
var filterResult = baseArr2.filter(function (item, index) {
return item.age > 20
})
console.log("filterResult", filterResult);
filter会遍历数组中所有的数据项,会返回一个新数组,数组中存放符合筛选条件的数据项,是不会改变原来数组的
find
- 遍历查找
- 根据回调函数中的条件,返回第一个符合条件的值
var findResult = baseArr2.find(function (item, index) {
return item.age > 20
})
console.log("findResult", findResult);
//打印结果是符合条件的那个数据项
findIndex
查找 根据回调函数中的条件,返回第一个符合条件的值的下标
var findIndexResult = baseArr2.findIndex(function (item, index) {
return item.age > 20
})
console.log("findIndexResult", findIndexResult);
查找成功会返回第一个符合条件数据项的下标,只会查找一个符合条件的值,当查找失败的时候会返回-1
reduce
- 累加
- 返回累加后的值(最后一次回调函数返回的值)
- 参数1:回调函数
- 参数1.1
prev:上一次回调函数的返回值(第一次是初始值) - 参数1.2
current:本次的数组元素item - 参数1.3
index:本次数组元素的下标index - 参数1.4
arr:原数组的引用 - 参数2
prev/0所在的位置:累加的初始值(如果没有设置初始值,则默认数组的第一个值就是初始值)
const arr=[1,2,34,53,3];
var reduceResult = arr.reduce(function (prev, current, index, arr) {
console.log("prev,current,index,arr", prev, current, index, arr);
//每次应该返回当次累加后的值,用以下一次累加
return prev + current;
},0);
console.log("reduceResult", reduceResult);