天天看点

数组遍历的几种用法---forEach()、map()、filter()、every()、some()

1、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]
           

无返回值,直接改变原来的数组

2、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]
           

会返回被处理之后的新数组

3、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]
           

主要用于筛选,返回筛选后的一个新数组

4、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

5、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

继续阅读