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

May 16, 2016 pm 03:50 PM

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.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles