A general traversal function that can be used to traverse objects and arrays. Arrays and pseudo-array objects containing a length attribute (pseudo-array objects such as the arguments object of a function) are traversed with a numerical index, from 0 to length-1, Other objects are traversed through their properties.
$.each() is different from $(selector).each(). The latter is specially used for traversing jquery objects. The former can be used to traverse any collection (whether it is an array or an object). If it is an array, the callback function will Pass in the index of the array and the corresponding value (the value can also be obtained through the this keyword, but JavaScript will always wrap this value as an object - whether it is a string or a number), and the method will return the traversed object. One parameter.
Example:————Pass in array
<script><br>
<br>
$.each([52, 97], function(index, value) {<br>
alert(index ‘: ‘ value);<br>
});<br>
<br>
</script>
//Output
0:52
1:97
Example:————If a map is used as a collection, the callback function passes in a key-value pair each time
<script><br>
<br>
var map = {<br>
‘flammable’: ‘inflammable’,<br>
‘duh’: ‘no duh’<br>
};<br>
$.each(map, function(key, value) {<br>
alert(key ‘: ‘ value);<br>
});<br>
<br>
</script>
//Output
flammable: inflammable
duh: no duh
Example:——You can exit $.each() when returning false in the callback function. If a non-false is returned, it will be like using continue in a for loop, and it will immediately enter the next traversal
<script><br>
var arr = [ "one", "two", "three", "four", "five" ];//array<br>
var obj = { one:1, two:2, three:3, four:4, five:5 }; // Object<br>
jQuery.each(arr, function() { // this specified value<br>
$(“#” this).text(“Mine is ” this “.”); // this points to the value of the array, such as one, two<br>
return (this != “three”); // If this = three, exit the traversal<br>
});<br>
jQuery.each(obj, function(i, val) { // i points to the key, val specifies the value<br>
$(“#” i).append(document.createTextNode(” – ” val));<br>
});<br>
</script>
// Output
Mine is one. – 1
Mine is two. – 2
Mine is three. – 3
- 4
- 5
Example:——Traverse the items of the array, passing in index and value
<script><br>
$.each( ['a','b','c'], function(i, l){<br>
alert( “Index #” i “: ” l );<br>
});<br>
<br>
</script>
例子:———遍历对象的属性,传入 key和value
<script><br>
<br>
$.each( { name: “John”, lang: “JS” }, function(k, v){<br>
alert( “Key: ” k “, Value: ” v );<br>
});<br>
<br>
</script>
正自评论的例子
1. 如果不想输出第一项 (使用retrun true)进入 下一遍历
<script><br>
<br>
var myArray=["skipThis", "dothis", "andThis"];<br>
$.each(myArray, function(index, value) {<br>
if (index == 0) {<br>
return true; // equivalent to ‘continue' with a normal for loop<br>
}<br>
// else do stuff…<br>
alert (index “: “ value);<br>
});<br>
<br>
</script>