继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

js数组遍历-Looping over arrays

1步
关注TA
已关注
手记 24
粉丝 120
获赞 651

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

from: xixi小站

打开App,阅读手记
2人推荐
发表评论
随时随地看视频慕课网APP