Home > Web Front-end > JS Tutorial > Detailed explanation of the use of jquery.map() method_jquery

Detailed explanation of the use of jquery.map() method_jquery

WBOY
Release: 2016-05-16 15:50:46
Original
1123 people have browsed it

The prototype method map is similar to each and calls the static method of the same name, except that the returned data must be processed by another prototype method pushStack method before returning. The source code is as follows:

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

This article mainly analyzes the static map method. As for pushStack, it will be analyzed in the next essay;

First understand the use of map (manual content)

$.map converts elements in one array to another array.

The conversion function as a parameter will be called for each array element, and the conversion function will be passed a parameter representing the element being converted.

The conversion function can return the converted value, null (removing the item from the array), or an array containing the value expanded into the original array.

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

is called for each array element, and the conversion function is passed a parameter representing the element being converted.

Function can return any value.

Alternatively, this function can be set to a string, and when set to a string, will be treated as a "lambda-form" (short form?), where a represents an array element.

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

Example 1:

//将原数组中每个元素加 4 转换为一个新数组。
//jQuery 代码:
$.map( [0,1,2], function(n){
 return n + 4;
});
//结果:
[4, 5, 6]

Copy after login

Example 2:

//原数组中大于 0 的元素加 1 ,否则删除。
//jQuery 代码:
$.map( [0,1,2], function(n){
 return n > 0 ? n + 1 : null;
});
//结果:
[2, 3]

Copy after login

Example 3:

//原数组中每个元素扩展为一个包含其本身和其值加 1 的数组,并转换为一个新数组
//jQuery 代码:
$.map( [0,1,2], function(n){
 return [ n, n + 1 ];
});
//结果:
[0, 1, 1, 2, 2, 3]

Copy after login

It can be seen that the map method is similar to the each method by looping through each object or "item" of the array to execute a callback function to operate the array or object, but the two methods also have many differences

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

For example:

var items = [1,2,3,4]; 
$.each(items, function() { 
alert('this is ' + this); 
}); 
var newItems = $.map(items, function(i) { 
return i + 1; 
}); 
// newItems is [2,3,4,5]
//使用each时,改变的还是原来的items数组,而使用map时,不改变items,只是新建一个新的数组。

var items = [0,1,2,3,4,5,6,7,8,9]; 
var itemsLessThanEqualFive = $.map(items, function(i) { 
// removes all items > 5 
if (i > 5) 
  return null; 
  return i; 
}); 
// itemsLessThanEqualFive = [0,1,2,3,4,5]

Copy after login

Back to the 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 );
  },

Copy after login

First, declare a few variables to prepare for the next traversal. The jsArray variable is used to simply distinguish objects and arrays. This Boolean compound expression is relatively long, but it is not difficult to understand as long as you remember the priority of js operators. Well, first the parentheses are executed first, then the logical AND>Logical OR>Congruent>assignment, and then you can analyze

First calculate in parentheses and then add length !== undefined and typeof length === "number to the result. The final result of these two necessary conditions is then logically ORed with elems instanceof jQuery. Simply put, it is isArray The situations that are true include:

1. elems instanceof jQuery is true, in other words, it is the jquery object

2. length !== undefined && typeof length === "number" and length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems) At least one of these three is established

Can be split into 3 small situations

length exists and is a number, and the length attribute of the array or array-like object to be traversed is greater than 0. length-1 exists. This ensures that it can be traversed, such as jquery objects, domList objects, etc.

length exists and is a number and the length attribute is equal to 0. If it is 0, it doesn’t matter, it will not be traversed

length exists and is a number and the object to be traversed is a pure array

After meeting these conditions, start traversing separately according to the result of isArray. For "array", use for loop, and for object, use for...in loop

// 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;
        }
      }

Copy after login

When it is an array or array-like, directly pass the value and pointer of each item of the loop and the arg parameter into the callback function for execution. The arg parameter is the parameter used internally in this method, which is very similar to each and some other jquery methods. , as long as null is not returned when executing the callback function, the result returned by the execution will be added to the new array. The same is true for object operations and directly skip

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

Finally, the result set is flattened. Why is this step required? Because map can expand arrays, this is the case in the previous third example:

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

If used in this way, the new array obtained is a two-dimensional array, so the dimensionality must be reduced

ret.concat.apply([], ret) is equivalent to [].concat.apply([], ret). The key function is apply, because the second parameter of apply divides the ret array into multiple parameters. Passing it to concat to convert a two-dimensional array into a one-dimensional array is worth collecting

A simple analysis of the map method has been completed. I hope you can correct me if there are any mistakes due to limited capabilities.

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template