欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JavaScript 变量和数据类型、数组的常用方法、流程控制、循环和 JSON 字符串 - 网络学习 - php 中文博客

最编程 2024-07-08 12:55:48
...
  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8" />
  • <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  • <title>js中的循环遍历</title>
  • </head>
  • <body>
  • <ul>
  • <li>item1</li>
  • <li>item2</li>
  • <li>item3</li>
  • </ul>
  • <script>
  • // 拿到第一个UL里的li
  • let ls= document.querySelectorAll('ul:first-of-type li');
  • console.log(ls);
  • var arr = [1,2,3,4,5];
  • // 1.for循环
  • for(var i=0; i<ls.length; i++){
  • ls[i].style.color = "red";
  • }
  • for(var i=0; i<arr.length; i++){
  • console.log(arr[i]);
  • }
  • // 2.while循环
  • var a = 0;
  • while(a < ls.length){
  • ls[a].style.color = "blue";
  • a++;
  • }
  • // 3.for-of循环
  • for (let item of ls) {
  • item.style.color = "cyan";
  • }
  • // 4.forEach()循环
  • ls.forEach(function(value,index,array){
  • console.log(value, index, array);
  • value.style.color = "pink";
  • });
  • // 5.for-in循环数组,for循环的简略版,比较合适数组使用
  • for (let index in arr) {
  • // console.log(index);
  • }
  • </script>
  • </body>
  • </html>
  • 推荐阅读