for...in,for...of等循环的区别应用

202 阅读1分钟

提到循环,我们往往会想到许多的方法,比如基础的for循环,while循环,forEach等,那我们简单盘点下这些循环的异同,然我们后续更好的使用它们。

for循环和while循环

for是最常见的循环,一般在知道数组长度的情况下进行判断循环,而while常作为条件循环,循环次数不定

// for循环,根据数组长度确定循环次数
const arr = [1,2,4]

for(let i = 0; i<arr.length; i++){ // i为数组的索引
  console.log(arr[i]);
}

// 1 2 4

// while循环,条件不满足式一直循环,循环次数不定
let count = 0 
while(count<4){
  console.log(count);
  count++
}
// 0 1 2 3

for...in和for...of

// 数组循环
const arr = [1,2,4]
Array.prototype.name='数组'

for(let item in arr){
  console.log(item);
}
// 0 1 2 name

for(let item of arr){
  console.log(item);
}

// 1 2 4
// 普通对象循环
const obj = {
  name:'对象',
  age:18
}

Object.prototype.address='地址'

for(let item in obj){
  console.log(item);
}
// name age address

for(let item of obj){
  console.log(item);
}
// TypeError: obj is not iterable
// Set对象
const set = new Set([1, 2, 4])

for(let item in set){
  console.log(item);
}
// undefined

for(let item of set){
  console.log(item);
}
// 1 2 4
// Map对象
const set = new Map([['apples', 500], ['bananas', 300], ['oranges', 200]])

for(let item in set){
  console.log(item);
}
// undefined

for(let item of set){
  console.log(item);
}
// [ 'apples', 500 ] [ 'bananas', 300 ] [ 'oranges', 200 ]

通过上面的列子我们可以得出以下结论

  • for...in 遍历的是对象的属性名(key),而for...of遍历的是对象的属性值(value)
  • for...in 以任意顺序遍历一个对象的除Symbol以外的可枚举属性,for...in不能遍历普通的对象,所以建议for...in遍历对象,for...of遍历数组
  • for...in 遍历那些可以枚举属性的对象,而for...of遍历那些可以迭代的对象
  • 然后在vue中存在长得很像的v-for...in和v-for...of,它们两个是一样的效果,都是遍历数组,使用是没有区别的

forEach和map

在数组中我们常常也会用的forEach,map等去遍历数组,那么它们又有什么区别呢

 const arr = [1,2,4]
 let a = []
 let b = []
 let c = []
 
 a = arr.forEach(item=>{
  return item
 })
 console.log(a)
 // undefined
 
 arr.forEach((item,index,arr)=>{
  c[index] = item + 1
  arr[index] = item + 2
 })
 console.log(arr)
 // [ 3, 4, 6 ]
 console.log(c)
 // [ 2, 3, 5 ]


 b = arr.map(item=>{
  return item + 1
 })
 console.log(b)
 // [ 2, 3, 5 ]

通过上面的列子我们可以得出以下结论

  • forEach是没有返回值的,map有返回值
  • map可以对数组中每一个元素进行操作并返回一个全新数组,forEach可以遍历给原数组中元素操作放入新的数组,也能改变原数组