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