JavaScript 开发或阅读代码时,会遇到forin语法的循环语句。这个循环语句到底会遍历什么数据?用于迭代具有可枚举属性的对象(除了Symbol内置对象).
迭代可枚举属性的顺序不确定的。
不适用于基于索引顺序的数组,因为不一定按照索引顺序迭代。如果是迭代数组,使用常规for...i循环或者使用数组的内置方法forEach(function(item)).
语法
for (variable in object)
statement
可使用let,const,var来声明variable.
可以在迭代循环里修改属性值.
使用对象内置的hasOwnProperty()方法来判断是否是直接属性,而不是继承过来的。
使用obj.propertyIsEnumerable(prop)来判断是否某个属性是否可枚举。
for...in是为了枚举对象属性构建的,常用在调试时输出到控制台。
<html>
<body>
<p id="out">for...inp>
body>
<script>
function print(str){
let p = document.createElement("p");
p.innerHTML = str;
document.body.append(p)
}
let visitData = {url:"https://blog.csdn.net/infoworld",action:"subcribe"};
print("1. 遍历可枚举属性.");
print("-- 修改属性前");
for(const p in visitData){
print(`${p}=${visitData[p]}`);
visitData[p] = "hello";
}
print("-- 修改属性后");
for(const p in visitData){
print(`${p}=${visitData[p]}`);
}
function User() {
this.color = 'red';
}
User.prototype = visitData;
print("2. 遍历继承的可枚举属性");
let user = new User();
for(const p in user)
print(`${p}=${user[p]}`);
print("3. 只遍历自身可枚举属性");
print("-- 修改属性前");
for(const p in user){
if(user.hasOwnProperty(p)){
print(`${p}=${user[p]}`);
user[p] = "world";
}
}
print("-- 修改属性后");
for(const p in user){
if(user.hasOwnProperty(p))
print(`${p}=${user[p]}`);
}
print("4. for...in不应该用于迭代一个关注索引顺序的 Array");
let jsonArray = ['https://blog.csdn.net/infoworld','Tobey'];
for(const i in jsonArray)
print(`${i}=${jsonArray[i]}`);
print("5. 使用数组forEach方法遍历数组");
jsonArray.forEach(one => {
print(one);
});
print("6. 遍历p元素可枚举属性");
const p = document.getElementById("out");
for(const prop in p){
print(`${prop}=${p[prop]}`);
}
script>
html>
for...in
1. 遍历可枚举属性.
-- 修改属性前
url=https://blog.csdn.net/infoworld
action=subcribe
-- 修改属性后
url=hello
action=hello
2. 遍历继承的可枚举属性
color=red
url=hello
action=hello
3. 只遍历自身可枚举属性
-- 修改属性前
color=red
-- 修改属性后
color=world
4. for...in不应该用于迭代一个关注索引顺序的 Array
0=https://blog.csdn.net/infoworld
1=Tobey
5. 使用数组forEach方法遍历数组
https://blog.csdn.net/infoworld
Tobey
6. 遍历p元素可枚举属性
align=
...