JavaScript 数组循环教程展示了如何在 JavaScript 中循环数组。我们可以使用 forEach 方法以及 for 和 while 语句遍历元素。
数组是许多值的集合。数组项称为数组的元素。
以下方法可用于在 JavaScript 中迭代数组的元素:
- forEach 方法 – 遍历数组元素
- for in – 遍历数组索引
- for of – 遍历数组值
- 经典 for – 使用计数器遍历数组
- 经典while循环 – 使用计数器遍历数组
使用 forEach 的 JavaScript 数组循环
forEach
方法为每个数组元素执行一次提供的函数。
const words = ['pen', 'pencil', 'falcon', 'rock', 'sky', 'earth']; words.forEach(e => console.log(e)); console.log('-------------------------'); words.forEach((e, idx) => console.log(`${e} has index ${idx}`));
我们有一个单词数组。使用 forEach
方法,我们遍历数组的元素并将它们打印到控制台。
words.forEach(e => console.log(e));
我们遍历数组的元素。
words.forEach((e, idx) => console.log(`${e} has index ${idx}`));
在这种形式中,我们有一个元素及其索引可供使用。
$ node foreach.js pen pencil falcon rock sky earth ------------------------- pen has index 0 pencil has index 1 falcon has index 2 rock has index 3 sky has index 4 earth has index 5
在下面的示例中,我们使用数字。
let vals = [1, 2, 3, 4, 5]; vals.forEach(e => console.log(e * e)) console.dir(vals); console.log('----------------'); let vals2 = vals.map(e => e * e); vals2.forEach(e => console.log(e)); console.dir(vals2);
我们对数组值应用数值运算。
let vals = [1, 2, 3, 4, 5];
我们有一组值。
vals.forEach(e => console.log(e * e))
我们遍历数组并为其所有元素供电。
console.dir(vals);
数组的内容用console.dir
显示。
let vals2 = vals.map(e => e * e);
使用map
函数,我们根据作为参数传递的函数创建一个新数组。
vals2.forEach(e => console.log(e));
我们遍历新创建的数组。
$ node foreach2.js 1 4 9 16 25 [ 1, 2, 3, 4, 5 ] ---------------- 1 4 9 16 25 [ 1, 4, 9, 16, 25 ]
使用 for in 的 JavaScript 数组循环
for in
构造用于遍历数组索引。
let words = ['pen', 'pencil', 'falcon', 'rock', 'sky', 'earth']; for (let idx in words) { console.log(`${words[idx]} has index ${idx}`); }
该示例遍历单词数组的索引。它打印单词及其索引。
$ node for_in.js pen has index 0 pencil has index 1 falcon has index 2 rock has index 3 sky has index 4 earth has index 5
JavaScript 数组循环与 for of
使用for of
构造,我们迭代数组的元素。
let words = ['pen', 'pencil', 'falcon', 'rock', 'sky', 'earth']; for (let word of words) { console.log(word); }
该示例打印words
数组中的所有单词。
带有经典 for 语句的 JavaScript 数组循环
JavaScript 支持经典的 C 风格的 for 语句。它使用一个辅助计数器变量来遍历数组。
for 循环包含三个阶段:初始化、条件和代码块执行以及递增。
let words = ['pen', 'pencil', 'falcon', 'rock', 'sky', 'earth']; for (let i=0; i<words.length; i++) { console.log(words[i]); }
该示例使用经典的 for 循环遍历单词数组。
for (let i=0; i<words.length; i++) {
i
变量是辅助计数器值。我们使用 length
属性确定数组的大小。
在第一阶段,我们将计数器i
初始化为零。这个阶段只做一次。接下来是条件。如果满足条件,则执行 for 块内的语句。在第三阶段,计数器增加。现在我们重复2、3阶段,直到不满足条件,离开for循环。在我们的例子中,当计数器等于数组的大小时,for 循环停止执行。
带有 while 语句的 JavaScript 数组循环
while 语句是一种控制流语句,允许根据给定的布尔条件重复执行代码。 while 关键字执行大括号括起来的块内的语句。每次表达式被评估为 true 时都会执行这些语句。
let words = ['pen', 'pencil', 'falcon', 'rock', 'sky', 'earth']; let i = 0; while (i < words.length) { console.log(words[i]); i++; }
while循环类似于for循环;我们有计数器变量,while 循环分为三个阶段。
在本教程中,我们介绍了几种在 JavaScript 中循环数组的方法。
列出所有 JavaScript 教程。