JavaScript 中 for...of 和 for...in 語句之間的區別是什麼?


for…in 迴圈

“for...in” 迴圈用於遍歷物件的屬性。

以下是語法 -

語法

for (variablename in object) {
statement or block to execute
}

你可以嘗試執行以下示例來實現“for-in”迴圈。這會列印 Web 瀏覽器的 Navigator 物件

示例

即時演示

<html>
<body>
<script>
var aProperty;
document.write("Navigator Object Properties<br /> ");

for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
</script>
</body>
</html>

for…of 迴圈

“for…of” 迴圈用於遍歷可迭代物件,其中包括 Map、Array、arguments 等。

語法

以下是語法 -

for (variablename of iterable){
statement or block to execute
}

示例

下面是一個顯示 for…of 迴圈遍歷的示例

即時演示

<!DOCTYPE html>
<html>
<body>
<script>
let itObj= [20, 30, 40, 50];

for (let res of itObj) {
res += 1;
document.write("<br>"+res);
}
</script>
</body>
</html>

輸出

21
31
41
51

更新日期:15-06-2020

204 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.