JS foreach
最后修改于 2023 年 10 月 18 日
在本文中,我们将展示如何在 JavaScript 中创建 foreach 循环。
C 语言普及了经典的 for 循环,使用计数器来创建循环。
foreach 循环逐个迭代数据集合。 在每个循环中,一个临时变量包含当前元素。
JavaScript 有 forEach
方法和 for/of
形式来循环遍历可迭代对象。
JS forEach 方法
在第一个例子中,我们使用 forEach
方法来遍历数组的元素。
foreach.js
let words = ['pen', 'pencil', 'falcon', 'rock', 'sky', 'earth']; words.forEach(e => console.log(e)); console.log("----------------------"); words.forEach((word, idx) => { console.log(`${word} has index ${idx}`); });
该示例循环遍历一个单词数组的元素。
words.forEach(e => console.log(e));
在第一个循环中,我们打印所有元素。
words.forEach((word, idx) => { console.log(`${word} 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
在下一个示例中,我们使用 forEach
方法来循环遍历一个 map。
foreach2.js
let stones = new Map([[1, "garnet"], [2, "topaz"], [3, "opal"], [4, "amethyst"]]); stones.forEach((k, v) => { console.log(`${k}: ${v}`); });
我们有一个小石头 map。 在每个循环中,该对被解构为键和值。
$ node foreach2.js garnet: 1 topaz: 2 opal: 3 amethyst: 4
JS for/of
for/of 语句循环遍历可迭代对象的序列值。
for_of.js
let words = ['pen', 'pencil', 'falcon', 'rock', 'sky', 'earth']; for (let word of words) { console.log(word); }
在示例中,我们使用 for/of 语句遍历单词数组。
在下一个示例中,我们遍历一个 map。
for_of2.js
let stones = new Map([[1, "garnet"], [2, "topaz"], [3, "opal"], [4, "amethyst"]]); for (let e of stones) { console.log(e); } console.log('------------------------'); for (let [k, v] of stones) { console.log(`${k}: ${v}`); }
我们有两个 for/of 循环。
for (let e of stones) { console.log(e); }
在第一个循环中,我们遍历元素。
for (let [k, v] of stones) { console.log(`${k}: ${v}`); }
在第二个循环中,我们将每个元素解构为键和值项。
$ node for_of2.js [ 1, 'garnet' ] [ 2, 'topaz' ] [ 3, 'opal' ] [ 4, 'amethyst' ] ------------------------ 1: garnet 2: topaz 3: opal 4: amethyst
来源
在本文中,我们使用 foreach 循环来遍历 JavaScript 中可迭代对象的元素。 我们使用了 forEach
方法和 for/of
语句。