数组遍历

187 阅读2分钟

forEach() 用于遍历数组无返回值,会改变原来数组中的值

let arr = [1, 3, 12, 2, 20, -1, 6, 17];
arr.forEach((item, index, array) => {
    array[index] = item * 2;
});
console.log(arr);					//	[2, 6, 24, 4, 40, -2, 12, 34]
// 无返回值,直接改变原来的数组

map() 用于遍历数组,返回处理之后的新数组

const arr = [1, 3, 12, 2, 20, -1, 6, 17];
const newArr = arr.map((item, index, array) => item * 2);
console.log(arr);					//	[1, 3, 12, 2, 20, -1, 6, 17]
console.log(newArr);					//	[2, 6, 24, 4, 40, -2, 12, 34]
// 会返回被处理之后的新数组

filter() 用于筛选数组中满足条件的元素,返回一个筛选后的新数组

const arr = [1, 3, 12, 2, 20, -1, 6, 17];
const newArr = arr.filter((item, index, array) => item < 5);
console.log(arr);					//	[1, 3, 12, 2, 20, -1, 6, 17]
console.log(newArr);					//	[1, 3, 2, -1]
// 主要用于筛选,返回筛选后的一个新数组

every() 用于判断数组中的每一项元素是否都满足条件,返回一个布尔值

const arr = [1, 3, 12, 2, 20, -1, 6, 17];
const bool = arr.every((item, index, array) => item < 12);
console.log(bool);					//	false
// 所有元素都满足条件返回true,只要有一个不满足则返回false

some() 用于判断数组中是否存在满足条件的元素,返回一个布尔值

const arr = [1, 3, 12, 2, 20, -1, 6, 17];
const bool = arr.some((item, index, array) => item < 12);
console.log(bool);					//	true
// 只要有一个满足条件的就返回true,如果所有都不满足则返回false

reduce() 主要用于数组累加

prev  // 它是上一次调用回调时返回的结果,每次调用的结果都会给prev
cur  // 当前的元素
index  // 当前的索引
arr  // 循环的数组
var a = [1,2,3,4,5,6,7,8,9,10]
var str = a.reduce(function(prev,cur,index,arr){
	return prev + cur ;
})
str  // 55; 返回函数累计处理的结果
// 将二维数组转换成一维数组
var a= [[0,1],[2,3],[4,5],[6,7],[8,9]];
 
var str = a.reduce(function(prev,cur){
	return prev.concat(cur)
})
 
str    //(10) [0,1, 2, 3, 4, 5, 6, 7, 8, 9]
// 数组去重
var arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
var str = arr.sort().reduce((prev, cur)=>{
    if(prev.length===0 || prev[prev.length-1]!==cur){
        prev.push(cur);
    }
    return prev;
}, []);
str // (5) [1, 2, 3, 4, 5]