for of
循环JavaScript for of
语句循环 通过可迭代对象的值。
它允许您循环遍历可迭代的数据结构 例如数组、字符串、映射、节点列表等:
for (variable of iterable) {
// code block to be executed
}
变量 - 对于每次迭代,下一个属性的值为 分配给变量。 变量可以用以下方式声明 const
、let
或 var
。
iterable - 具有可迭代属性的对象。
For/of 于 2015 年添加到 JavaScript (ES6)
Safari 7 是第一个支持以下功能的浏览器:
Chrome 38 | Edge 12 | Firefox 51 | Safari 7 | Opera 25 |
Oct 2014 | Jul 2015 | Oct 2016 | Oct 2013 | Oct 2014 |
Internet Explorer 不支持For/of。
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x;
}
自己尝试一下→
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of any iterable object:</p>
<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>
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x;
}
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of an iterable object.</p>
<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>
while
循环和 do/while
循环将在下一章中解释。