Detailed explanation of Jquery $. map usage example

  • 2021-08-10 06:43:42
  • OfStack

The $. map () function is used to process each element (or each attribute of an object) in an array using the specified function and to encapsulate the processing result as a new array return.


1. Before jQuery 1.6, this function only supported traversing arrays; Starting from 1.6, this function also supports traversing objects.

2. map () also passes in two arguments to the function: Its 1 is the element or attribute value of the current iteration, and its 2 is the array index or object attribute name of the current iteration item.

3. The return value of this function will be one element in the result array, and if the return value is null or undefined, it will not be added to the result array.

$.map(data,function(item,index){return XXX})

Traverse each element in the data array, and form a new element according to the calculation method in return, and put it into the returned array

var b = $.map( [55,1,2], function( item,index ) { return { "label": item, "value": index }});
            alert(b[0].label +" "+ b[0].value);

[55, 1, 2] is an array. According to the condition of return, when item in,,, and function is 55, index, that is, the subscript of the array is 0

$. map () is equivalent to a loop in parentheses

Loop multiple pieces of data and define the data as b

var array = [0, 1, 52, 97];
array = $.map(array, function(a, index) {
 return [a - 45, index];

The output is:

[-45, 0, -44, 1, 7, 2, 52, 3]

Related articles: