for in能遍历数组与对象的可枚举属性,但是不仅遍历对象内部,而且会遍历原型链(若只遍历对象内部,配合obj.hasOwnProperty(【属性】))
for of,(ES6增加)能遍历数组,但是不能遍历对象(ES6遍历对象内部可用Symbol.iterator)
demo
var a = {"name": 'Lucky', age: 12, sayName: function() { alert(this.name)}};
var b = ["Day",2,3];
var ele;
for (ele in a) {
console.log(ele +':' + a[ele]); //输出属性名称及属性值
}
for (ele in b) {
console.log(ele + ':' + b[ele]);//输出属性名称及属性值
}
for (ele of b) {
console.log(ele); //输出数组属性值
}
/*报错:VM3258 v.asp:19 Uncaught TypeError: a[Symbol.iterator] is not a function(…)*/for (ele of a) {
console.log(ele +':' + a[ele]);
}