案例:forEach和some區別


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>

  <body>
    <script>
      var arr = ["red", "green", "blue", "pink", "red"];
      // 1. forEach迭代 遍歷
      // arr.forEach(function(value) {
      //     if (value == 'green') {
      //         console.log('找到了該元素');
      //         return true; // 在forEach 里面 return 不會終止迭代
      //     }
      //     console.log(11);

      // })
      // 如果查詢數組中唯一的元素, 用some方法更合適,
      arr.some(function(value) {
        if (value == "red") {
          console.log("找到了該元素:" + value);
          return true; //  在some 里面 遇到 return true 就是終止遍歷 迭代效率更高
        }
        console.log(11);
      });
      // arr.filter(function(value) {
      //     if (value == 'green') {
      //         console.log('找到了該元素');
      //         return true; //  // filter 里面 return 不會終止迭代
      //     }
      //     console.log(11);

      // });
    </script>
  </body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM