JavaScript 中的 for...in 和 for...of 迴圈有什麼區別?
for...in 和 for...of 迴圈的區別
這兩個迴圈都用於迭代,但它們迭代的物件不同。
1) for...in 迴圈
此迴圈以任意順序迭代物件的**可列舉屬性**。它只關心屬性,而不關心值。
在下面的例子中,使用**for...in**迴圈迭代陣列的**屬性**。由於它是一個數組,**索引**是一個重要的屬性,因此將迭代並顯示每個元素的索引。 除了索引之外,還會顯示一些繼承屬性,例如“**inherProp2**”、“**inherProp1**”。
示例-1
<html>
<body>
<script>
Object.prototype.inherProp1 = function() {};
Array.prototype.inherProp2= function() {};
var org = ["Apple", "Microsoft", "Tesla"]
org.anotherOrg = "solarCity";
for (var key in org) {
document.write(key);
document.write("</br>");
}
</script>
</body>
</html>輸出
0 1 2 anotherOrg // own property inherProp2 // inherited property inherProp1 // inherited property
在下面的示例中,由於使用了**hasOwnProperty()**,因此只顯示自己的屬性,例如**索引**和其他屬性,而不會顯示繼承的屬性,例如“**inherProp1**”和“**inherProp2**”。
示例-2
<html>
<body>
<script>
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
var org = ["Apple", "Microsoft", "Tesla"]
org.anotherOrg = "solarCity";
for (var i in org) {
if (org.hasOwnProperty(i)) {
document.write(i);
document.write("</br>");
}
}
</script>
</body>
</html>輸出
0 1 2 anotherOrg
2) for...of 迴圈
與**for...in**迴圈不同,**for...of**迴圈迭代物件定義要迭代的值。
在下面的示例中,使用**for...of**迴圈在輸出中顯示'**Apple**'、'**Microsoft**'和'**Tesla**'等屬性。
示例
<html>
<body>
<script>
var org = ["Apple", "Microsoft", "Tesla"]
for (var key of org) {
document.write(key);
document.write("</br>");
}
</script>
</body>
</html>輸出
Apple Microsoft Tesla
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP