jstips Looping over arrays
JS语言中有很多遍历数组的方法。我们从几个较为传统的遍历方式开始,逐步向大家展示标准的遍历方法。
while
let index = 0;
const array = [1, 2, 3, 4, ,5];
while (index < array.length) {
console.log(array[index]);
index++;
}
for(最传统的形式)
const array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i ++) {
console.log(array[i]);
}
forEach
const array = [1, 2, 3, 4, 5];
array.forEach((current_value, index, arr) => {
console.log(current_value, index);
});
map
forEach这中方法,并不返回一个新的数组。map函数对数组的每个元素上应用一个函数,并返回一个全新的数组。map是immutable的,更加的安全。
//.map(current_value, index, array)
const array = [1, 2, 3, 4, 5];
const square = x => Math.pow(x, 2);
const squares = array.map(square);
console.log(`Original array: ${array}`);
console.log(`Squared array: ${squares}`);
reduce
reduce函数对数组的每个元素执行累加器,最后返回一个值。
const array = [1, 2, 3, 4, 5];
const sum = (x, y) => x + y;
const array_sum = array.reduce(sum, 0);
console.log(`The sum of array: ${array} is ${array_sum}`);
filter
对一个数组实施过滤
const array = [1, 2, 3, 4, 5];
const event = x => x % 2 === 0;
const event_arr = array.filter(event);
console.log(event_arr);
every
判断一个数组上的元素是否全部符合某种条件
const array = [1, 2, 3, 4, 5, 6];
const under_seven = x => x < 7;
if (array.every(under_seven)) {
console.log('Every element in the array is less than 7');
} else {
console.log('At least one element in the array was bigger than 7');
}
some
判断一个数组上的元素是否至少有一个符合某种条件
const array = [1,2,3,9,5,6,4];
const over_seven = x => x > 7;
if (array.some(over_seven)) {
console.log('At least one element bigger than 7 was found');
} else {
console.log('No element bigger than 7 was found');
}