var arr = ['a', 'b', 'c', 'd']; for (let a in arr) { console.log(a); // 0 1 2 3 } for (let a of arr) { console.log(a); // a b c d }
for...of
不能循环普通的对象,需要通过和Object.keys()
搭配使用
var student={ name:'wujunchuan', age:22, locate:{ country:'china', city:'xiamen', school:'XMUT' } } for(var key of Object.keys(student)){ //使用Object.keys()方法获取对象key的数组 console.log(key+": "+student[key]); } // name: wujunchuan // age: 22 // locate: [object Object]
总结
- for in得到对对象的key或数组,字符串的下标
- for of和forEach一样,是直接得到值,forEach中途不能return 或者break
- for of不能对象用