工具函数之$.each()

$.each():对数组或对对象内容进行循环处理

语法:
jQuery.each( collection, callback(indexInArray, valueOfElement) )
参数:
collection   遍历的对象或数组
callback(indexInArray, valueOfElement) 在每一个对象上调用的函数
$.each()说明:
一个通用的遍历函数 , 可以用来遍历对象和数组. 数组和含有一个length属性的伪数组对象 (伪数组对象如function的arguments对象)以数字索引进行遍历,从0到length-1,其它的对象通过的属性进行遍历.

$.each()与$(selector).each()不同:
1.后者专用于jquery对象的遍历, 前者可用于遍历任何的集合(无论是数组或对象)
2.如果是数组,回调函数每次传入数组的索引和对应的值(值亦可以通过this关键字获取,但javascript总会包装this值作为一个对象—尽管是一个字符串或是一个数字)
3.方法会返回被遍历对象的第一参数。

eg.
回调函数每次传入数组的索引和对应的值
<script>
     $.each([52, 97], function(index, value) {
          alert(index + ‘: ‘ + value);
     });
</script>

一个映射作为集合使用,回调函数每次传入一个键-值对
<script>
     var map = {
          ‘flammable’: ‘inflammable’,
          ‘duh’: ‘no duh’
     };
     $.each(map, function(key, value) {
          alert(key + ‘: ‘ + value);
     });
</script>

值亦可以通过this关键字获取,但javascript总会包装this值作为一个对象—尽管是一个字符串或是一个数字)
回调函数中 return false时可以退出$.each()
<script>
     var arr = [ "one", "two", "three", "four", "five" ];//数组
     var obj = { one:1, two:2, three:3, four:4, five:5 }; // 对象
   
     //值通过this关键字获取
     jQuery.each(arr, function() {  // this 指定值
          $(“#” + this).text(“Mine is ” + this + “.”);  // this指向为数组的值, 如one, two
          return (this != “three”); // 如果this = three 则退出遍历
     });
   
     //回调函数每次传入一个键-值对
     jQuery.each(obj, function(i, val) {  // i 指向键, val指定值
     $(“#” + i).append(document.createTextNode(” – ” + val));
     });
</script>

(使用retrun true)进入 下一遍历
<script>
     var myArray=["skipThis", "dothis", "andThis"];
     $.each(myArray, function(index, value) {
          if (index == 0) {
               return true; // equivalent to ‘continue’ with a normal for loop
          }
          // else do stuff…
     alert (index + “: “+ value);
     });
</script>

 

你可能感兴趣的:(each)