JavaScript中数组的常用操作之数组的遍历
for..of 循环
for(const item of items)循环遍历数组项,如下所示遍历list列表:
const list = ['aaa', 'bbb', 'ccc'];
for (const item of list) {
console.log(item);
// 可以随时使用break语句停止遍历。
}
// > 'aaa'
// > 'bbb'
// > 'ccc'
for 循环
for(let i; i < array.length; i++)循环使用递增的索引变量遍历数组项。
for通常需要在每个循环中递增index 变量
index变量从0递增到list.length-1。此变量用于按以下索引访问项: list [index]。
const list = ['aaa', 'bbb', 'ccc'];
for (let index = 0; index < list.length; index++) {
const item = list[index];
console.log(item);
// 可以随时使用break语句停止遍历
}
// > 'aaa'
// > 'bbb'
// > 'ccc'
array.forEach() 方法
array.forEach(callback)方法通过在每个数组项上调用callback函数来遍历数组项。
在每次遍历中,都使用以下参数调用callback(item [, index [, array]]):(当前遍历项,当前遍历索引,数组本身)。
const list = ['aaa', 'bbb', 'ccc'];
list.forEach((value, index)=> {
console.log(value, index);
// 不能中断array.forEach()迭代
});
// > 'aaa', 0
// > 'bbb', 1
// > 'ccc', 2








网友评论