最新通知
js 数组Iteration"遍历的方法"
阅读次数:592 最后编辑时间:2022年04月07日

概述

Iteration “遍历的方法”

1.[].forEach


作用:每个元素执行一次提供的函数;

传参:(callback(当前元素,索引,该数组));

返回值:无;

实例

//标准用法
array.forEach(callback(currentValue, index, array){
    //do something
}, this)

2.[].find


作用:返回数组中满足提供的测试函数的第一个元素的值;

传参:(callback(当前元素,索引,该数组));

返回值:该元素;([].findIndex()返回索引);

实例

//标准用法
array.find(callback(currentValue, index, array){
     //do something
}, this)

let num = [1,2,3];
console.log(num.find( value => {
    if(value === 2){
        return true;
    }
    return false;
}));  // 2

3.[].filter


作用:创建一个新数组, 其包含通过所提供函数实现的测试的所有元素;

传参:(callback(当前元素,索引,该数组));

返回值:通过测试的元素的集合的数组;

实例

//标准用法
let arr = array.filter(callback(currentValue, index, array){
    //do something
}, this)

4.[].map


作用:创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果;

传参:(callback(当前元素,索引,该数组));

返回值:一个新数组,每个元素都是回调函数的结果;

实例

//标准用法
let numbers = [1, 4, 9];
let roots = numbers.map(Math.sqrt);
// roots的值为[1, 2, 3]
//numbers的值仍为[1, 4, 9]

5.[].every


作用:测试数组的所有元素是否都通过了指定函数的测试;

传参:(callback(当前元素,索引,该数组));

返回值:true或false;

实例

//标准用法
function isBigEnough(element, index, array) {
    return (element >= 10);
}
let passed = [12, 5, 8, 130, 44].every(isBigEnough);    // passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);    // passed is true

6.[].some


作用:测试数组的某些元素是否都通过了指定函数的测试;

传参:(callback(当前元素,索引,该数组));

返回值:true或false;

实例

//标准用法
function isBigEnough(element, index, array) {
    return (element >= 10);
}
let passed = [1, 5, 8, 3, 4].some(isBigEnough);    // passed is false
passed = [2, 4, 18, 13, 4].some(isBigEnough);    // passed is true

7.[].reduce


作用:对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值;

传参:(callback(累加器accumulator,当前元素,索引,该数组));

返回值:函数累计处理的结果;

实例

//标准用法
let total = [0, 1, 2, 3].reduce((sum, value) => {
    return sum + value;
}, 0);
// total is 6

let flattened = [[0, 1], [2, 3], [4, 5]];
flattened.reduce((a, b) => {
    return a.concat(b);
}, []);

// flattened is [0, 1, 2, 3, 4, 5]

8.[].entries


作用:返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对;

传参:无;

返回值:一个新的 Array 迭代器对象;

实例

//标准用法
var arr = ["a", "b", "c"];
var iterator = arr.entries();// undefined
console.log(iterator);// Array Iterator {}
console.log(iterator.next().value); // [0, "a"]
console.log(iterator.next().value); // [1, "b"]
console.log(iterator.next().value); // [2, "c"]

9.[].values


作用:数组转对象;

传参:无;

返回值:一个新的 Array 迭代器对象;

实例

//标准用法
let arr = ['w', 'y', 'k', 'o', 'p'];
let eArr = arr.values();    // 您的浏览器必须支持 for..of 循环

// 以及 let —— 将变量作用域限定在 for 循环中
for (let letter of eArr) {
    console.log(letter);
}