1.for of 无法遍历对象
var obj={
name:"jack",
age:18,
weight:120
}
for(let i in obj){
console.log(i,obj[i],"for in")
}
for(let j of obj){
console.log(j,obj[j],"for of")
}
打印后提示 obj is not iterable
2.遍历输出结果不同
for in 遍历数组的索引,for of直接遍历数组的值
var arr=["jack","nick","neo","leo"]
for(let i in arr){
console.log(i)
}
console.log("----------------------------")
for(let j of arr){
console.log(j)
}
遍历字符串
let name="jacky"
for(var i in name){
console.log(i);
}
console.log('----------------------');
for(var j of name){
console.log(j);
}
3.for in 会遍历自定义属性,而for of不会
var arr = ["jack","nick","neo","leo"]
arr.name = "mike";
for(var i in arr){
console.log(i,arr[i]);
}
console.log('----------------------');
for(var j of arr){
console.log(j);
}
for in 输出了name,而for of没有输出,可能是由于上面说的for of无法输出对象的原因?有错误请大佬指出~谢谢!