for…of 是 ES6 新增的遍历方式,允许遍历一个含有 iterator 接口 的数据结构(数组、对象等)并且返回各项的值,和 ES3 中的 for… in 的区别如下
for…of 遍历获取的是对象的键值,for…in 获取的是对象的键名;
for… in 会遍历对象的整个原型链,性能非常差不推荐使用,而 for … of 只遍历当前对象不会遍历原型链;
对于数组的遍历,for…in 会返回数组中所有可枚举的属性(包括原型链上可枚举的属性),for…of 只返回数组的下标对应的属性值;
总结:for...in 循环主要是为了遍历对象而生,不适用于遍历数组; for...of只要有迭代器都可以遍历,比如数组、类数组对象,字符串、Set、Map 以 及 Generator 对象。
let arr = ['a','b','c']for ( key in arr) { console.log(key)//0,1,2}
let obj = { a:'aa', 1:'11', e:'b', c:'c', 2:'22', 0:'00'}for(key in obj) { console.log(key)//012aec }
需要注意:对象会默认给数字键排序,字符串不会进行排序。
let arr = ['e','b','c'] for(key of arr){ console.log(key)//e b c } let obj = { a:'aa', 1:'11', e:'b', c:'c', 2:'22', 0:'00' } let arrObj = [ {name:'1',age:18}, {name:'2',age:19}, {name:'a',age:20}, {name:'b',age:21}, {name:'0',age:22}, ] for(key of arrObj){ console.log(key)//item } for(key of obj){ console.log(key)//ypeError: obj is not iterable }