• 循环结构(for/in 语句、for/of语句以及for of与for in 区别)


    for/in 语句

    用于循环对象属性。

    循环中的代码每执行一次,就会对数组的元素或者对象的属性进行一次操作。

    for-in循环实际是为循环”enumerable“对象而设计的。

    例如:循环对象属性

    1. <script>
    2. // for/in 语句用于循环对象属性。
    3. {
    4. let person = {fname:'John',lname:'Doe',age:15}
    5. // 定义text变量的目的,用了存储 对象中的属性
    6. let text = "";
    7. // 定义索引变量名
    8. let x;
    9. for(x in person){
    10. console.log(x);
    11. // 正确的写法
    12. console.log(person[x]);
    13. // 错误的写法
    14. // console.log(person.x);
    15. // text += person[x]+" ";
    16. text += "person." + x + ":" + person[x]+"
      "
    17. }
    18. console.log('查看: '+text);
    19. document.write('查看: '+text)
    20. }
    21. script>

    console输出预览效果

      for/of语句

    for/of 在 2015 年被添加到 JavaScript (ES6)。

    for-of的语法看起来跟for-in很相似,但它的功能却丰富的多,它能循环很多东西。

    语法

    for (索引变量名 of 数组/对象){ 
        在此执行代码
    }

    for (let a of object) {
     //a代表数组/对象中 每一项内容
     执行的代码块
    }

     Internet Explorer 不支持 for/of

    for of与for in 区别

    区别(1):不能直接遍历对象(for of无法循环遍历对象)

    1. {
    2. let person = {fname:'John',lname:'Doe',age:15}
    3. let text = '';
    4. let x;
    5. for(x of person){
    6. console.log(x);
    7. }
    8. }

    console输出预览效果

    注意: for/in可以遍历对象 for/of不能直接遍历对象(如上现象)

     区别(2):for/in   for/of 遍历数组,遍历输出结果不同

    1. {
    2. //区别(2):for/in for/of 遍历输出结果不同
    3. let arr = ['tom','jerry','elva','lili'];
    4. // key 输出的是 数组中每个单元所对应的索引
    5. for(let key in arr){
    6. console.log(key);
    7. }
    8. // item 输出的是 数组中每个单元所对应的内容
    9. for(let item of arr){
    10. console.log(item);
    11. }
    12. }

    console输出预览效果

     

    区别(3):for in 会遍历自定义属性,for of不会 

    for in 能够遍历到数组的索引;for of 不会。

    1. // 区别(3):for in 会遍历到 自定义属性,for of不会
    2. // for in 能够遍历到数组的索引;for of 不会
    3. // 如果我们在数组上自定义一个属性
    4. // 例如 arr.name = '小芮'
    5. {
    6. var arr = ['nick','freddy','mike','james'];
    7. arr.name = '小芮';
    8. for(let key in arr){
    9. console.log(key + '===' + arr[key]);
    10. }
    11. for(let key of arr){
    12. console.log(key);
    13. }
    14. }

    console输出预览效果

     例如:循环遍历数组对象

    1. // for/of 遍历数组对象
    2. {
    3. var arr = [
    4. {name:'nick',age:18},
    5. {name:'freddy',age:24},
    6. {name:'mike',age:26},
    7. {name:'james',age:34},
    8. ];
    9. // 对象中的属性获取方式 对象名.属性名
    10. for(let item of arr){
    11. console.log(item.name, item.age);
    12. }
    13. }

    console输出预览效果

  • 相关阅读:
    Flask框架——flask-caching缓存
    数据赋能(171)——开发:数据挖掘——概述、关注焦点
    国产猫罐头的真实水准怎么样?真实水准好的猫罐头推荐
    java-常用正则操作
    父子组件通信的属性验证 validator
    DSA之图(1):什么是图
    统计学三大相关系数介绍及代码实现
    【luogu P4590】游园会(DP套DP)
    数据分析--matplotlib绘图
    linux Shell 命令行-02-var 变量
  • 原文地址:https://blog.csdn.net/m0_71814235/article/details/126287232