for of
和 for in
都是用来遍历的属性
for...in
语句用于遍历数组或者对象的属性(对数组或者对象的属性进行循环操作)。for in
得到对对象的key
或数组,字符串的下标for of
和forEach
一样,是直接得到值for of
不能用于对象const obj = { a: 1, b: 2, c: 3 } for (let i in obj) { console.log(i) //输出 : a b c } for (let i of obj) { console.log(i) //输出: Uncaught TypeError: obj is not iterable 报错了 }
说明: for in
和 for of
对一个obj对象
进行遍历,for in 正常的获取了对象的 key值,分别打印 a、b、c,而 for of却报错了。
const arr = ['a', 'b', 'c'] // for in 循环 for (let i in arr) { console.log(i) //输出 0 1 2 } // for of for (let i of arr) { console.log(i) //输出 a b c }
for in
特点function Foo() { this[100] = 'test-100' this[1] = 'test-1' this["B"] = 'bar-B' this[50] = 'test-50' this[9] = 'test-9' this[8] = 'test-8' this[3] = 'test-3' this[5] = 'test-5' this["A"] = 'bar-A' this["C"] = 'bar-C' } var bar = new Foo() for(key in bar){ console.log(`index:${key} value:${bar[key]}`) }
//输出: index:1 value:test-1 index:3 value:test-3 index:5 value:test-5 index:8 value:test-8 index:9 value:test-9 index:50 value:test-50 index:100 value:test-100 index:B value:bar-B index:A value:bar-A index:C value:bar-C
总结一句: for in 循环特别适合遍历对象。
①. for of
知识点补充:
1、推荐在循环对象属性的时候使用 for...in,在遍历数组的时候的时候使用 for...of
2、for...in 循环出的是 key,for...of 循环出的是 value
3、注意,for...of 是 ES6 新引入的特性。修复了 ES5 引入的 for...in 的不足
4、for...of 不能循环普通的对象(如通过构造函数创造的),需要通过和 Object.keys()搭配使用
for in遍历数组的毛病:
1.index索引为字符串型数字,不能直接进行几何运算
2.遍历顺序有可能不是按照实际数组的内部顺序
3.使用for in会遍历数组所有的可枚举属性,包括原型。例如上栗的原型方法method和name属性
所以for in更适合遍历对象,不要使用for in遍历数组。
那么除了使用for循环,如何更简单的正确的遍历数组达到我们的期望呢(即不遍历method和name),ES6中的for of更胜一筹.
遍历对象
遍历对象 通常用for in来遍历对象的键名