• for in和for of


    for/in

    用于遍历对象的所有属性,for/in主要用于遍历对象,不建议用来遍历数组。

    遍历数组操作

    let hd = [
      { title: "第一章 走进JAVASCRIPT黑洞", lesson: 3 },
      { title: "ubuntu19.10 配置好用的编程工作站", lesson: 5 },
      { title: "媒体查询响应式布局", lesson: 8 }
    ];
    document.write(`
      <table border="1" width="100%">
      <thead><tr><th>标题</th><th>课程数</th></thead>
    `);
    for (let key in hd) {
      document.write(`
      <tr>
      <td>${hd[key].title}</td>
      <td>${hd[key].lesson}</td>
      </tr>
      `);
    }
    document.write("</table>");

    遍历对象操作

    let info = {
      name: "后盾人",
      url: "houdunren.com"
    };
    for (const key in info) {
      if (info.hasOwnProperty(key)) {
        console.log(info[key]);
      }
    }

    遍历window对象的所有属性

    for (name in window) {
      console.log(window[name]);
    }

    for/of

    用来遍历 Arrays(数组), Strings(字符串), Maps(映射), Sets(集合)等可迭代的数据结构。

    与 for/in 不同的是 for/of 每次循环取其中的值而不是索引。

    let arr = [1, 2, 3];
    for (const iterator of arr) {
        console.log(iterator);
    }

    遍历字符串

    let str = 'houdunren';
    for (const iterator of str) {
        console.log(iterator);
    }

    使用迭代特性遍历数组

    const hd = ["hdcms", "houdunren"];
    
    for (const [key, value] of hd.entries()) {
      console.log(key, value); //这样就可以遍历了
    }

    使用for/of 也可以用来遍历DOM元素

    <body>
      <ul>
        <li></li>
        <li></li>
      </ul>
    </body>
    <script>
      let lis = document.querySelectorAll("li");
      for (const li of lis) {
        li.addEventListener("click", function() {
          this.style.backgroundColor = "red";
        });
      }
    </script>
  • 相关阅读:
    恢复 root 本地无权限 Access denied for user 'root'@'localhost' (using password: NO)
    linux 下 PHP Notice: session_start(): ps_files_cleanup_dir 报错 问题剖析
    linux 下mysql 开启远程连接
    linux 下mysql 字段插入的值超过 预设大小报错
    CSS、HTML5、JS
    WPF、Sivelright、UWP
    Quartz.net作业调度
    nginx+iis、NLB、Web Farm、Web Garden、ARR
    workflow
    SqlSugar ORM
  • 原文地址:https://www.cnblogs.com/yyy1234/p/15827690.html
Copyright © 2020-2023  润新知