Jquery. map () and jquery. map

Source: Internet
Author: User

Jquery. map () and jquery. map

Similar to each, the prototype method map calls a static method of the same name, but the returned data must be processed by another prototype method pushStack. The source code is as follows:

map: function( callback ) {    return this.pushStack( jQuery.map(this, function( elem, i ) {      return callback.call( elem, i, elem );    }));  },

This article mainly analyzes the static map method as to pushStack's analysis in the next article;

First, understand the use of map (manual content)

$. Map converts the elements in an array to another array.

The conversion function, as a parameter, calls each array element and transmits an element to the conversion function as a parameter.

The conversion function can return the converted value, null (delete items in the array), or an array containing values, and extend it to the original array.

Parameters
ArrayOrObject, callbackArray/Object, FunctionV1.6
ArrayOrObject: array or object.

Each array element is called, And a converted element is passed as a parameter to the conversion function.

Function returns any value.

In addition, this function can be set to a string. When it is set to a string, it will be treated as "lambda-form" (abbreviated form ?), A Indicates an array element.

For example, "a * a" indicates "function (a) {return a * ;}".

Example 1:

// Add 4 to each element in the original array to form a new array. // JQuery code: $. map ([0, 1, 2], function (n) {return n + 4;}); // result: [4, 5, 6]

Example 2:

// Add 1 to element 0 in the original array; otherwise, delete the array. // JQuery code: $. map ([0, 1, 2], function (n) {return n> 0? N + 1: null;}); // result: [2, 3]

Example 3:

// Each element in the original array is extended to an array containing its own and its value plus 1, and converted to a new array // jQuery code: $. map ([0, 1, 2], function (n) {return [n, n + 1] ;}); // result: [0, 1, 1, 2, 2, 3]

It can be seen that the map method and the each method are similar to implementing the callback function by looping every object or the "item" of the array to perform operations on the array or object. However, there are many differences between the two methods.

For example, each () returns the original array and does not create a new array, while map creates a new array. The each traversal is that this points to the current array or object value, map points to the window, because in the source code, the object is not impersonate like each;

For example:

Var items = [1, 2, 4]; $. each (items, function () {alert ('this is '+ this) ;}); var newItems =$. map (items, function (I) {return I + 1 ;}); // newItems is [2, 3, 4, 5] // when using each, the original items array is changed, when map is used, items is not changed, but a new array is created. Var items = [,]; var itemslessthan1_five = $. map (items, function (I) {// removes all items> 5 if (I> 5) return null; return I ;}); // itemslessthan1_five =, 4, 5]

Back to map source code

// arg is for internal usage only  map: function( elems, callback, arg ) {    var value, key, ret = [],      i = 0,      length = elems.length,      // jquery objects are treated as arrays      isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;    // Go through the array, translating each of the items to their    if ( isArray ) {      for ( ; i < length; i++ ) {        value = callback( elems[ i ], i, arg );        if ( value != null ) {          ret[ ret.length ] = value;        }      }    // Go through every key on the object,    } else {      for ( key in elems ) {        value = callback( elems[ key ], key, arg );        if ( value != null ) {          ret[ ret.length ] = value;        }      }    }    // Flatten any nested arrays    return ret.concat.apply( [], ret );  },

First, declare several variables to prepare for the next traversal. The jsArray variable is used to distinguish objects and arrays, this Boolean compound expression is long, but it is hard to understand it as long as you remember that the js operators are prioritized. First, parentheses are prioritized and then values are assigned to logic and logic or full, then you can analyze it.

First, calculate in parentheses and then add length to the result! = Undefined and typeof length = "number. The final result of the two necessary conditions is then used to perform logical or operation with elems instanceof jQuery. Simply put, the following situations are true for isArray:

1. elems instanceof jQuery is true. In other words, it is a jquery object.

2. length! = Undefined & typeof length = "number" and length> 0 & elems [0] & elems [length-1]) | length = 0 | jQuery. isArray (elems), which must have at least one

It can be split into three small cases.

Length exists and is a number, and the length attribute such as the array or class array to be traversed is greater than 0 length-1, so that it can be traversed, such as for the jquery object domList object, etc.

Length exists and is a number and the length attribute is equal to 0. If it is 0, it does not matter.

Length is a number and the object to be traversed is a pure array.

After these conditions are met, we start to traverse the data separately based on the isArray results. We use the for loop for the "array" and the for... in loop for the object.

// Go through the array, translating each of the items to their    if ( isArray ) {      for ( ; i < length; i++ ) {        value = callback( elems[ i ], i, arg );        if ( value != null ) {          ret[ ret.length ] = value;        }      }

When an array or an array of classes is used, the values, pointers, and arg parameters of each loop are directly transferred to the callback function for execution. The arg parameter is a parameter used inside the method, similar to each and some other jquery methods, the returned results are added to the new array as long as no null is returned when the callback function is executed. The object operation is also skipped directly.

// Flatten any nested arrays    return ret.concat.apply( [], ret );

Finally, flat the result set. Why is this step? Because map can expand the array, this is the case in the first 3rd examples:

$.map( [0,1,2], function(n){ return [ n, n + 1 ];});

If this is the case, the new array is a two-dimensional array, so the dimension must be reduced.

Ret. concat. apply ([], ret) is equivalent to []. concat. the key role of apply ([], ret) is apply, because the second parameter of apply divides the ret array into multiple parameters and passes it to concat to convert the two-dimensional array into one-dimensional array.

The simple analysis of the map method is complete, and the limited capability error may be corrected.

The above is all the content of this article. I hope you will like it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.