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 in 遍历的是数组的key值,就是下标,而for of却遍历的是value值,就是数据本身,遍历数组的话,for of写法更加简单,不用在像for in 一样通过下表去区值了,遍历数组建议用for of.
遍历对象:
var es6 ={
edition: 6,
committee: "TC39",
standard: "ECMA-262"};for(let e in es6){
console.log(e);}
// edition
// committee
// standard
for(let e of es6){
console.log(e);}
// TypeError: es6 is not iterable
对于普通的对象,for…in循环可以遍历键名,for…of循环会报错,所以遍历对象的话还是用for in比较合适,遍历数组的话用for of 更加合适哦。