当前位置: 首页 > 工具软件 > Fortune.js > 使用案例 >

js for-in / for-of

夏侯宏旷
2023-12-01
<!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>
    <style>
      ul {
        list-style: none;
      }
      li {
        border: solid 1px #ddd;
        height: 50px;
        width: 150px;
      }
    </style>

    <ul>
      <li></li>
      <li></li>
      <li></li>
    </ul>

    <script>
      let lis = document.querySelectorAll("li");
      for (const li of lis) {
        console.log(li);
        li.addEventListener("click", function () {
          li.style.backgroundColor = "red";
        });
      }

      // 例子1
      // let cx = ["chen", "xiu"];
      // for (let key in cx) {
      //   // console.log(key);
      //   console.log(cx[key]);
      // }

      // 例子2:for-in 输出表格
      let hd = [
        { title: "尼日尔用", lesson: "课程1" },
        { title: "尼日尔用2", lesson: "课程2" },
        { title: "尼日尔用3", lesson: "课程3" },
      ];

      document.write(`
        <table border="1" width="100%">
        <thead><tr><th>标题</th><th>课程书</th></thead>
      `);
      for (let i in hd) {
        document.write(`
        <tr><td>${hd[i].title}</td><td>${hd[i].lesson}</td></tr>
      `);
      }
      document.write(`</table>`);

      // 例子3
      let cx = ["chen", "xiu"];
      for (const iterator of cx) {
        console.log(iterator);
      }
    </script>
  </body>
</html>

 类似资料: