欢迎光临
我们一直在努力

js遍历数组

遍历数组

有几种在JavaScript中循环数组的方法。我们将从经典的开始,

while

let index = 0;
const array = [1,2,3,4,5,6];

while (index < array.length) {
  console.log(array[index]);
  index++;
}

for (classical)

const array = [1,2,3,4,5,6];
for (let index = 0; index < array.length; index++) {
  console.log(array[index]);
}

forEach

const array = [1,2,3,4,5,6];

array.forEach(function(current_value, index, array) {
  console.log(`At index ${index} in array ${array} the value is ${current_value}`);
});
// => undefined

map

最后一个构造是有用的,但是它不会返回一个新的数组,这可能对您的具体情况不合适。map通过在每个元素上应用一个函数来解决这个问题,然后返回新的数组。

const array = [1,2,3,4,5,6];
const square = x => Math.pow(x, 2);
const squares = array.map(square);
console.log(`Original array: ${array}`);
console.log(`Squared array: ${squares}`);

map的完整用法是:array .map(current_value, index, array).

reduce

From MDN:

reduce() 将累数组中的每个元素(从左到右)应用到一个单独的值。

const array = [1,2,3,4,5,6];
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,6];
const even = x => x % 2 === 0;
const even_array = array.filter(even);
console.log(`Even numbers in array ${array}: ${even_array}`);

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');
}

 

赞(0)
版权归原作者所有,如有侵权请告知。达维营-前端网 » js遍历数组

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址