一個通用的遍歷函數 , 能夠用來遍歷對象和數組. 數組和含有一個length屬性的僞數組對象 (僞數組對象如function的arguments對象)以數字索引進行遍歷,從0到length-1, 其它的對象經過的屬性進行遍歷.javascript
$.each()與$(selector).each()不一樣, 後者專用於jquery對象的遍歷, 前者可用於遍歷任何的集合(不管是數組或對象),若是是數組,回調函數每次傳入數組的索引和對應的值(值亦能夠經過this 關鍵字獲取,但javascript總會包裝this 值做爲一個對象—儘管是一個字符串或是一個數字),方法會返回被遍歷對象的第一參數html
<!DOCTYPE html> <html> <head> <script src=」http://code.jquery.com/jquery-latest.js」></script> </head> <body> <script> $.each([52, 97], function(index, value) { alert(index + ‘: ‘ + value); }); </script> </body> </html> //輸出 0: 52 1: 97
<!DOCTYPE html> <html> <head> <script src=」http://code.jquery.com/jquery-latest.js」></script> </head> <body> <script> var map = { ‘flammable’: ‘inflammable’, ‘duh’: ‘no duh’ }; $.each(map, function(key, value) { alert(key + ‘: ‘ + value); }); </script> </body> </html> //輸出 flammable: inflammable duh: no duh
<!DOCTYPE html> <html> <head> <style> div { color:blue; } div#five { color:red; } </style> <script src=」http://code.jquery.com/jquery-latest.js」></script> </head> <body> <div id=」one」></div> <div id=」two」></div> <div id=」three」></div> <div id=」four」></div> <div id=」five」></div> <script> var arr = [ "one", "two", "three", "four", "five" ];//數組 var obj = { one:1, two:2, three:3, four:4, five:5 }; // 對象 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> </body> </html> // 輸出 Mine is one. – 1 Mine is two. – 2 Mine is three. – 3 - 4 - 5
1. 若是不想輸出第一項 (使用retrun true)進入 下一遍歷 <!DOCTYPE html> <html> <head> <script src=」http://code.jquery.com/jquery-latest.js」></script> </head> <body> <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> </body> </html>
<!DOCTYPE html> <html> <head> <script src=」http://code.jquery.com/jquery-latest.js」></script> </head> <body> <script> $.each( ['a','b','c'], function(i, l){ alert( 「Index #」 + i + 「: 」 + l ); }); </script> </body> </html>
<!DOCTYPE html> <html> <head> <script src=」http://code.jquery.com/jquery-latest.js」></script> </head> <body> <script> $.each( { name: 「John」, lang: 「JS」 }, function(k, v){ alert( 「Key: 」 + k + 「, Value: 」 + v ); }); </script> </body> </html>