常用for循环和for in 以及for of 的区别

用Es6对象扩展运算符(…)与rest运算符说明

function test (...a) {
  for (let val = 0; val < a.length; val++) {
    console.log(val + ' ' + '常用的 for循环') // 0-7 便利出下标
  }

  for (let val in a) {
    console.log(val + ' ' + 'for in  0-7 便利出下标') // 0-7 便利出下标
  }

  for (let val of a) {
    console.log(val + ' ' + 'for of 1-8 便利值') // 1-8 便利值
  }
}
test(1, 2, 3, 4, 5, 6, 7, 8)

 补充一个可以用for of 同样能实现for in效果的方式

for…of数组索引:有时候开发中是需要数组的索引的,那我们可以使用下面的代码输出数组索引。

let arr=['xzblogs','小智','zachary']
for (let index of arr.keys()){
    console.log(index);
}

可以看到这时的控制台就输出了0,1,2,也就是数组的索引。

用for of还可以同时输出对应的索引值和对应的内容,也就是键值对

我们用entries()这个实例方法,配合我们的for…of循环就可以同时输出内容和索引了。

let arr=['xzblogs','小智','zachary']
for (let [index,val] of arr.entries()){
    console.log(index+':'+val);
}

 利用in来遍历 key 为数字的数据列表

let data = {
  '6': { 'value'10 },
  '7': { 'value'12 }
}

for (const key in data) {
  console.log(key, data[key].value) 
  // 打印出 
 6 10
 7 12 
}
let arr = [
  { 'sort': 1, 'nane': 1 },
  { 'sort': 2, 'nane': 2 },
  { 'sort': 3, 'nane': 3 }
]

for (const keys in arr[0]) {
  console.log(keys) // 打印出   sort  nane
}

for (const keys in arr) {
  console.log(keys) // 打印出   0 1 2
}
原文地址:https://www.cnblogs.com/Model-Zachary/p/7088977.html