• 常用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
    }
  • 相关阅读:
    【转】ThinkPHP 页面跳转
    thinkphp中select()和find()的区别
    (Python)异常处理try...except、raise
    python中try except处理程序异常的方法
    SNMP消息传输机制
    公钥私钥+数字证书原理
    转:使用python的Flask实现一个RESTful API服务器端
    转:xxe attack学习
    转:php防止sql注入的一点心得
    转:在 Ubuntu 上使用 Nginx 部署 Flask 应用
  • 原文地址:https://www.cnblogs.com/Model-Zachary/p/7088977.html
Copyright © 2020-2023  润新知