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>