JS数组的高级方法有:
1:forEach( ) 循环遍历数组
2:every( ) 遍历数组,返回值遇到false时遍历终止 相比于forEach()多了一个return false
3:map( ) 修改并返回新的数组
4:find( ) 找到数组的第一个元素
5:findIndex( ) 找到数组的第一个元素的下标
6:some( ) 找到数组的第一个元素返回值为找到为true或找不到为false
7:flatMap( ) 把数组里面的二维数组拉平成为一个一维数组
8:reduce( ) 数组求和运算
9:filter( ) 数组过滤器
直接上演示案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>数组的高级方法</title>
</head>
<body>
<script>
var array = [1, 2, 3];
// forEach()循环遍历数组
// 数组名.forEach(function (变量名) {});
array.forEach(function (item) {
console.log(item);
});
// map()修改并返回新的数组
// var 新数组名 = 数组名.map(function ([变量]) { return 参数 修改的全部数组或变量名的条件 修改部分数组 });
var newArray1 = array.map(function () {
return 1;
});
console.log(newArray1);
var newArray2 = array.map(function (item) {
return (item = item > 2 ? item : 5);
});
console.log(newArray2);
// find()找到数组的第一个元素
// 数组名.find(function(变量名){ return 变量名的条件 })
console.log(
array.find(function (item) {
return item == 1;
})
);
// findIndex()找到数组的第一个元素的下标
// 数组名.findIndex(function(变量名){ return 变量名的条件 })
console.log(
array.findIndex(function (item) {
return item == 1;
})
);
// some()找到数组的第一个元素返回值为找到为true或找不到为false
// 数组名.some(function(变量名){ return 变量名的条件 })
console.log(
array.some(function (item) {
return item == 1;
})
);
// every()遍历数组,返回值遇到false时遍历终止 相比于forEach()多了一个return false
// 数组名.every(function (变量名) { [return false;] });
array.every(function (item) {
console.log(item);
return false;
});
// flatMap()把数组里面的二维数组拉平成为一个一维数组
// 数组名.flatMap(function(变量名){ return 变量名 })
var array2 = [1, 2, 3, [1], [2]];
console.log(
array2.flatMap(function (item) {
return item;
})
);
// reduce()数组求和运算
// 数组名.reduce(function (累加变量名,变量名){ return 累加变量名 + 变量名 })
console.log(
array.reduce(function (sum, item) {
return (sum += item);
})
);
// filter()数组过滤器
// 数组名.filter(function (变量名){ return 变量名的条件 })
console.log(
array.filter(function (item) {
return item > 5 ? item : 10;
})
);
</script>
</body>
</html>