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 ); })); },
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]
Example 2:
//原数组中大于 0 的元素加 1 ,否则删除。 //jQuery 代码: $.map( [0,1,2], function(n){ return n > 0 ? n + 1 : null; }); //结果: [2, 3]
Example 3:
//原数组中每个元素扩展为一个包含其本身和其值加 1 的数组,并转换为一个新数组 //jQuery 代码: $.map( [0,1,2], function(n){ return [ n, n + 1 ]; }); //结果: [0, 1, 1, 2, 2, 3]
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]
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 ); },
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; } }
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 );
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 ]; });
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.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!
