JavaScript - 可迭代对象
在 JavaScript 中,可迭代对象是指可以使用 for...of 循环进行迭代的对象。它们也可以使用其他方法进行迭代,例如 forEach()、map() 等。
基本上,您可以在 JavaScript 中遍历可迭代对象的每个元素。
以下是一些常见可迭代对象的示例。
- Array
- String
- Map
- Set
- Arguments
- NodeList
- TypedArrays
- Generators
使用 for...of 循环进行迭代
在本节中,我们将使用 for...of 循环遍历 Map 中的数组元素、字符串字符、集合元素和键值对。
示例:迭代数组
在下面的代码中,我们定义了一个数组,使用 for...of 循环遍历数组。
代码在输出中打印数组的每个元素。
<html>
<body>
<div>Iterating the array: </div>
<div id = "demo"></div>
<script>
const output = document.getElementById("demo");
const array = ["Hello", "Hi", 10, 20, 30];
// 迭代数组
for (let ele of array) {
output.innerHTML += ele + ", ";
}
</script>
</body>
</html>
输出
Iterating the array: Hello, Hi, 10, 20, 30,
示例:遍历字符串
在下面的代码中,我们使用 for...of 循环遍历每个字符串字符。
该代码在输出中打印以逗号分隔的字符串字符。
<html>
<body>
<div id = "demo">Iterating a string: </div>
<script>
const output = document.getElementById("demo");
let str = "Hello";
// 迭代字符串
for (let char of str) {
output.innerHTML += char + ", ";
}
</script>
</body>
</html>
输出
Iterating a string: H, e, l, l, o,
示例:迭代集合
在本例中,我们创建了一个包含多个元素的集合。之后,我们遍历集合中的每个元素并打印输出。
<html>
<body>
<p id = "demo">Iterating the Set: </p>
<script>
const output = document.getElementById("demo");
const set = new Set([10, 20, 30, 40, 40, 50, 50]);
// 迭代集合
for (let ele of set) {
output.innerHTML += ele + ", ";
}
</script>
</body>
</html>
输出
Iterating the Set: 10, 20, 30, 40, 50,
示例:迭代 map
在下面的示例中,我们定义了一个包含 3 个键值对的 map。在 for...of 循环的每次迭代中,我们都从 map 中获取一个键值对。
<html>
<body>
<div id = "demo">Iterating the Map: <br></div>
<script>
const output = document.getElementById("demo");
const map = new Map([
["1", "one"],
["2", "two"],
["3", "three"],
]);
// 迭代数组
for (let ele of map) {
output.innerHTML += ele + "<br>";
}
</script>
</body>
</html>
输出
Iterating the Map: 1,one 2,two 3,three
使用 forEach() 方法进行迭代
在本节中,我们使用 forEach() 方法对可迭代对象进行迭代。
示例
在下面的示例中,我们使用 forEach() 方法对数组进行迭代,并在输出中打印数组中的每个元素。
<html>
<body>
<div> Using the forEach() method: </div>
<div id="demo"></div>
<script>
const output = document.getElementById("demo");
const array = [true, false, 50, 40, "Hi"];
// 迭代数组
array.forEach((ele) => {
output.innerHTML += ele + ", ";
})
</script>
</body>
</html>
输出
Using the forEach() method: true, false, 50, 40, Hi,
使用 map() 方法进行迭代
在本节中,我们使用 map() 方法对可迭代对象进行迭代。
示例
在下面的示例中,map() 方法与数组一起使用。在 map() 方法的回调函数中,我们打印数组元素。
<html>
<body>
<p id = "demo">Using the map() method: </p>
<script>
const output = document.getElementById("demo");
const array = [true, false, 50, 40, "Hi"];
// 迭代数组
array.map((ele) => {
output.innerHTML += ele + ", ";
})
</script>
</body>
</html>
输出
Using the map() method: true, false, 50, 40, Hi,
但是,您可以使用 for 循环、while 循环等循环来遍历数组、字符串等。JavaScript 还允许我们定义自定义迭代器来遍历可迭代对象。

