JS数组的迭代

2次阅读

共计 1435 个字符,预计需要花费 4 分钟才能阅读完成。

forEach
forEach() 方法对数组的每个元素执行一次提供的函数。
var array1 = [‘a’, ‘b’, ‘c’];

array1.forEach(function(element) {
console.log(element);
});

// expected output: “a”
// expected output: “b”
// expected output: “c”
forEach() 是没有办法中止或者跳出循环的,除非抛出一个异常。
map
map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
map() 与 forEach() 的区别是 map 返回一个循环处理后的数组,不改变原数组的值,而 forEach 则只是遍历一遍数组,执行提供的函数。
for of
for…of 语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
let iterable = [10, 20, 30];

for (const value of iterable) {
console.log(value);
}
// 10
// 20
// 30
关于 for…of 语句遍历更多用法 mdn
filter
filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
var words = [‘spray’, ‘limit’, ‘elite’, ‘exuberant’, ‘destruction’, ‘present’];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array [“exuberant”, “destruction”, “present”]
reduce
reduce() 方法对数组中的每个元素执行一个由您提供的 reducer 函数 ( 升序执行),将其结果汇总为单个返回值。
const array1 = [1, 2, 3, 4];
// 1 + 2 + 3 + 4
console.log(array1.reduce((accumulator, currentValue) => accumulator + currentValue));
// expected output: 10
every
every() 方法测试数组的所有元素是否都通过了指定函数的测试。
function isBigEnough(element, index, array) {
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true
some
some() 方法测试是否至少有一个元素通过由提供的函数实现的测试。对于放在空数组上的任何条件,此方法返回 false。
[2, 5, 8, 1, 4].some(x => x > 10); // false
[12, 5, 8, 1, 4].some(x => x > 10); // true

正文完
 0