七、For of

116 阅读2分钟

For & ForEach

在es5中有许多方法循环数组
最为经典的就是for循环了

let array = [1,2,3];
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

除了for循环,我们还可以使用forEach循环

let array = [1,2,3];
array.forEach(function (value) {
  console.log(value);
});
// 1
// 2
// 3

写法上稍微有些简短,但是却有很多不足:
1、不能使用break跳出循环或者用continue到下一个循环
2、不能使用return,从封闭函数中返回

For In

for-in循环是为了遍历对象的属性设计的,如下:

var obj = {a:1,b:2};
for (let prop in obj) {
    console.log(prop);
}
// a
// b

如果我们把这个用在数组上,其实也是可以的

let array = [10,20,30];
for (let index in array) {
  console.log(index);
});
// 0
// 1
// 2

但是如果我们尝试着输出index,你会发现

let array = [10,20,30];
for (let index in array) {
  console.log(typeof(index));
};
// string
// string
// string

index都是字符串而不是数字,使用for-in数组把索引都变成了字符串
==注:所以如果你期望用数字去计算的话,可能就得注意了,可能会出现"1"+"2"得到"12"的结果,而不是3,还会把原型上的可枚举元素遍历出来,尝试下面例子==

Array.prototype.method=function(){
&emsp;&emsp;console.log(this.length);
}
var myArray=[1,2,4,5,6,7]
myArray.name="数组"
for (var index in myArray) {
  console.log(myArray[index]);
}

For-of 循环

对比于for-in循环,在es6中有个比较大的改变,就是for-of

let array = [10,20,30];
for (var value of array) {
  console.log(value);
}
// 10
// 20
// 30
  • 这算是通过==数组==元素循环的最简洁的方法
  • 它避免了很多陷阱
  • 他能使用break,continue和return

总结

  • for-in比较适合循环对象的属性
  • for-of比较适合遍历数组的值 ==for-of不只是可以遍历数组,他也可以遍历类数组对象,包括Set和Map类型==