ES6 FOR OF 循环

介绍

本文是在学习ES6时做的一些学习笔记,所有的笔记请查看:ES6 学习笔记

FOR…OF 循环

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  const fruits= ['apple','banana','orange','Mango']// for循环比较繁琐
  for(let i=0;i<fruits.length;i++){
      console.log(fruits[i])
  }
  
  // foreach循环不能终止,只能遍历数据
  // 即不可以使用continue、break
  fruits.foreach(fruit=>{
      console.log(fruit)
  })
  // for in 循环遍历的是可枚举属性,
  // 如果添加fruits.describe='my favorite frut'
  // 在下列遍历中也会输出 'my favorite frut'
  for(index in fruits){
      console.log(fruits[index]);
  }
  
  // for of 循环输出属性值,且只遍历输出数字属性(即通过下表可以查找),
  // 不会遍历非数字属性,即 添加fruits.describe='my favorite frut'
  // 'my favorite frut'不会被输出,
  // 而且可以使用  break 和 continue 
  for(let fruit of fruits){
      console.log(fruit)// 输出 'apple','banana','orange','Mango'
  }
  
  for(let fruit of fruits){
      if(fruit === 'Apple'){
          continue;
      }
      console.log(fruit)
  }
  
  

</script>

</body>
</html>

for of 循环用来遍历可迭代对象,可迭代对象指的是有iterable接口的。
在这里插入图片描述
函数中next()函数,可以手动调用来获取数组中的值。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  const fruits= ['apple','banana','orange','Mango']// for of 循环输出属性值,且只遍历输出数字属性,
  for(let [index,fruit] of fruits.entries())){
     console.log(`${fruit} ranks ${index+1} in my favorite `)
  }
  
</script>

</body>
</html>

for of 循环暂时不支持遍历对象。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  const fruits= ['apple','banana','orange','Mango']function sum(){
      let total = 0;
      for(let num in arguments){
          total = total + num;
      }
      return total;
  }
  sum(10,23,45);
  
  // for of 循环用于字符串
  let name='lavarist';
  for(let temp of name){
      console.log(temp);// l a v a r i s t
  }
  
  
</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
  .completed{
      color:red;
  }
</style>
<body>
<ul>
   <li>go to store</li>
  <li>watche tv</li>
  <li>go shopping</li>
</ul>
<script>
// for of 遍历可迭代对象 nodelist类型(非数组)
const list=document.querySelectALL('li');
for (let li of list){
    li.addEventListener('click',function{
        this.classList.toggle('completed')
    })
}
 
</script>
</body>
</html>
发布了25 篇原创文章 · 获赞 18 · 访问量 1001

猜你喜欢

转载自blog.csdn.net/MoonNight608/article/details/104148624
今日推荐