天天看點

$.each()和$().each()用法

$.each(obj, fn)

一個通用的疊代函數,可用于近似地疊代對象和數組。

這個函數與$().each()不同,$().each()是專門用于疊代和執行jQuery對象的函數。而這個函數可以用于疊代任何對象和數組。 這個函數的回調中包含兩個參數:第一個是key(對象)或index(數組),第二個是值。

傳回值:Object

參數:

obj (Object): 要重複疊代的對象或數組

fn (Function): 要在每個對象中執行的函數

示例:

這是一個疊代數組中所有項目的例子,通過函數通路了其中的每個項目和索引。

$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });

這是一個疊代對象中所有屬性的例子,通過函數通路了每個屬性的名稱和值。

$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); });

$.each( obj, fn )

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. This function is not the same as $().each() - which is used to iterate, exclusively, over a jQuery object. This function can be used to iterate over anything.

The callback has two arguments:the key (objects) or index (arrays) as the first, and the value as the second.

If you wish to break the each() loop at a particular iteration you can do so by making your function return false. Other return values are ignored.

Return value: Object

Parameters:

obj (Object): The object, or array, to iterate over.

fn (Function): The function that will be executed on every object.

Example:

This is an example of iterating over the items in an array, accessing both the current item and its index.

This is an example of iterating over the properties in an Object, accessing both the current item and its key.