js、es6中常见的几种迭代器

178 阅读2分钟

首先,列举我们用的几种迭代器:

  1. for循环
  2. for in
  3. for of 
  4. forEach
  5. map


  • for循环

let arr = []
for (var i = 0;i<6;i++){
    a[i] = function(){
    console.log(i)
    }
}
a[3]()  //打印结果为6
那么如何才能打印出正确的i值呢?
1、引入let
for (let i = 0;i<6;i++){
    a[i] = function(){
    console.log(i)
    }
}

2、把每次循环中的i保存下来
for (var i = 0;i<6;i++){
  var i = j;
 a[i] = function(){
 console.log(j)
}

这里放一个关于let深入的链接,感兴趣的小伙伴可以去看一下:zhuanlan.zhihu.com/p/28140450

  • for in  VS  for of

for in 循环:

var a=[1,2,3];
for(let i in a){
	console.log(i);//0 1 2
	console.log(a[i]);//1 2 3
}

for of 循环:

var a=[1,2,3];
for(let i of a){
	console.log(i);//1 2 3
}

从上面两个例子不难看出for in 遍历结果是key,而for of 遍历结果是 value。因此可以想到,for in更适合用于对象的遍历,for of 更适合用于数组的遍历。

那么,用for of遍历对象会发生什么呢???

 var obj = {
   'name': 'Jim Green',
   'age': 12
 }
 
 for(let key of obj) {
   console.log('for of obj', key)
 }
 // Uncaught TypeError: obj is not iterable

ES6 中引入了 Iterator,只有提供了 Iterator 接口的数据类型才可以使用 for of 来循环遍历,而 ArraySetMap、某些类数组如 arguments 等数据类型都默认提供了 Iterator 接口,所以它们可以使用 for of 来进行遍历。
  • forEach()  VS map()

let arr = [1,2,3]
let newArr1 = arr.forEach((v, i) => {
    console.log(v,i)
    return v*2
});
console.log(newArr1) //undefined

let newArr2 = arr.map((v,i)=>{
    return v*2
})
console.log(newArr2) //[2,4,6]

forEach()是这样定义的: 针对每一个元素执行提供的函数(executes a provided function once for each array element)。

map()是这样定义的:创建一个新的数组,其中每一个元素由调用数组中的每一个元素执行提供的函数得来(creates a new array with the results of calling a provided function on every element in the calling array)。

let arr = [1,2,3]
let newArr1 = arr.forEach((v, i) => {
    console.log(v,i)
    return arr[i] = v*2
});
console.log(newArr1,arr) // undefined  [2,4,6]

从上边这个🌰 可以看出,forEach() 不会返回有意义的值,但是会改变原数组。所以,如果需要对数组本本身做一些操作可以用forEach(),如果只是用数组中的数据做一些事情比如,根据后端返回数据动态加载出标签,就可以用map()