美文网首页
JavaScript数组的遍历

JavaScript数组的遍历

作者: 段煜华 | 来源:发表于2020-01-13 19:34 被阅读0次

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

相关文章

网友评论

      本文标题:JavaScript数组的遍历

      本文链接:https://www.haomeiwen.com/subject/bgynactx.html