for of 不能遍历对象,for in 可以
对比两段对象的遍历代码
for in
let b = {m: 1,n: 2,p: 3,q: 4}
for (let i in b) {
if (i == "p") {
break
}
console.log(i,b[i]);
}
运行结果为:
m 1
n 2
for of
let b = {m: 1,n: 2,p: 3,q: 4}
for (let i of b) {
if (i == "3") {
break
}
console.log(i,b[i]);
}
运行则会报错
两者都可以遍历数组,for in 可以遍历出键和值,for of 只能遍历出值
对比两段数组的遍历代码
for in
let a = ['c', 'd', 'e', 'f']
for (let i in a) {
if (i == 2) {
break
}
console.log(i,a[i]);
}
运行结果为:
0 c
1 d
for of
let a = ['c', 'd', 'e', 'f']
for (let i of a) {
if (i == "e") {
break
}
console.log(i);
}
运行结果为
c
d
网友评论