For Of 循环
JavaScript for of
语句循环遍历可迭代对象的值。
它允许您循环遍历可迭代的数据结构,例如数组、字符串、映射、节点列表等:
语法
for (variable of iterable) {
// code block to be executed
}
variable - 对于每次迭代,下一个属性的值都会分配给变量。变量可以用 const、let 或 var 声明。
iterable - 具有可迭代属性的对象。
遍历数组
<!DOCTYPE html>
<html lang="en">
<body>
<P id="demo"></P>
<script>
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
<!--
BMW
Volvo
Mini
-->
遍历字符串
<!DOCTYPE html>
<html lang="en">
<body>
<P id="demo"></P>
<script>
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
<!--
J
a
v
a
S
c
r
i
p
t
-->