jQuery 的 each 和 ES5 的 forEach 以及 art-template 的模板语法的 each 遍历 的分析对比

350 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

jQuery 的 each 和 ES5 的 forEach 以及 art-template 的模板语法的 each 遍历 的分析对比

 一、jQuery 的 each 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script src="引入相关的jQuery版本"></script>
  <script>
    
    // IE 8 不支持 高版本的jQuery ,在较低版本jQuery 2以下的时候可以运行,
     // 遍历 jQuery 元素
     $.each(['123', '234', '345'], function (index, item) {
       console.log(item)  // 123  234 345
     })

  </script>
</body>
</html>
  1. jQuery 对象的原型链中没有 forEach,对象的原型链是 Object.prototype;
  2. jQuery 不是专门用来遍历 jQuery 元素的, 可以在不兼容 forEach 的低版本浏览器中使用 jQuery 的 each 方法;
  3. 一般伪数组是对象的时候会使用jQuery的each来遍历
  4. $('div').each(function) 一般用于遍历 jQuery 选择器选择到的伪数组实例对象
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>

  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <script src="node_modules/jquery/dist/jquery.js"></script>
  <script>

    // 遍历body中的div元素
    $('div').each(function (index, item) {
       console.log(item)
     })

  </script>
</body>
</html>

 二、ES5 的 forEach

  1.  forEach 是 EcmaScript 5 中的一个数组遍历函数,是 JavaScript 原生支持的遍历方法 可以遍历任何可以被遍历的成员
  2. 由于 forEach 是 EcmaScript 5 中的,所以低版本浏览器不支持
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>

  <script src="node_modules/jquery/dist/jquery.js"></script>
  <script>

    // forEach 的 item, index 顺序和 jQuery 的正好相反   
   ;['lutian', 'lzp', 'love'].forEach(function (item, index) {
    console.log(item)
    })

  </script>
</body>
</html>

    3.也可以用forEach 来遍历 div元素,但是利用[].slice.call($('div'))先将其换成数组。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>

  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <script src="node_modules/jquery/dist/jquery.js"></script>
  <script>

   ;[].slice.call($('div')).forEach(function (item) {console.log(item)})

  </script>
</body>
</html>

 三、art-template 的模板语法的 each 遍历

// 这是 art-template 模板引擎支持的语法,只能在模板字符串中使用
{{each 数组}}
  <li>{{ $value }}</li>
{{/each}} 
<script id="test" type="text/html">
<h1>{{title}}</h1>
<ul>
    {{each list as value i}}
        <li>索引 {{i + 1}} :{{value}}</li>
    {{/each}}
</ul>

</script>