zoukankan      html  css  js  c++  java
  • 常用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
    }
  • 相关阅读:
    【Vue原理】Compile
    vue v-cloak 的作用和用法
    vue中template的作用及使用
    Vue-router 嵌套路由
    Vue keep-alive实践总结
    Vuex入门(2)—— state,mapState,...mapState对象展开符详解
    mysql允许外部连接设置
    Swagger入门教程
    牛客枚举题---铺地毯
    牛客区间求和、枚举、贪心题---数学考试
  • 原文地址:https://www.cnblogs.com/Model-Zachary/p/7088977.html
Copyright © 2011-2022 走看看