当前位置:网站首页>5.for in 和 for of区别和使用

5.for in 和 for of区别和使用

2022-07-31 08:39:00 道长道长IOT

直接上代码,有注释,有内容
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <script>
    const arr = ['goods',2,3,4,5,'a','b']
    for(let item in arr){
    
      console.log(item);
    }
    // for in 遍历的是数组的下标,也就是他的索引值,这里打印的结果就是0,1,2,3,4,5,6
    // 所以说其实for in 不适合于数组的遍历,他更适合于遍历普通的对象、同时for in 还可以拿到原型链上的对象
    const obj  = {
    
      name: '何志伟',
      age: 18,
    }
    for (let inkey in obj){
    
      console.log('in对象---' + inkey);
      // 这里打印name,age
      console.log(obj[inkey]);
      // 这里打印的是 何志伟 18
    }

    // for of 更适合于遍历一个数组,他会打印里面所有的值
    for(let ofkey of arr){
    
      console.log('of-----数组-' + ofkey);
      // 这里打印'goods',2,3,4,5,'a','b'
    }

    // 也可以使用for of 获得对象的属性
    let obj2 = {
     name:"张三", age:25, address:"深圳", getName:function(){
    } } 
    for(let ofKey of Object.keys(obj2)){
    
      console.log(ofKey);
    }

  </script>
  
</body>
</html>
原网站

版权声明
本文为[道长道长IOT]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_56986233/article/details/126010860