


Example analysis of how makeArray() in jQuery converts multiple types into JS native Array
jQuery.makeArray(obj) It’s easy to guess its purpose from the name: it should be used to convert the incoming object into a native array
Let’s take a look at the official website for more information. Explanation: Convert an array-like object into a true JavaScript array.(Convert an array-like object into a JS native array)
So what kind of object can be called " What about "array-like object"? Don’t rush to answer this question. I believe you will understand after reading the article. Let’s take a look at the following experiment first
Convert HTMLCollection into native Array
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery.makeArray demo</title> <style> p { color: red; } </style> <script src="//code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p> First </p> <p> Second </p> <p> Third </p> <p> Fourth </p> <script> // Returns a NodeList var elems = document.getElementsByTagName("p"); // Convert the NodeList to an Array var arr = jQuery.makeArray(elems); // Use an Array method on list of dom elements arr.reverse(); $(arr).appendTo(document.body); </script> </body> </html>
Here you can see how to use document in chrome .getElementsByTagName("p") returns an HTMLCollection
instead of the NodeList mentioned on the official website. I specifically looked for the difference between NodeList and HTMLCollection: HTMLCollection object and NodeList objectVery similar, but the former may be accessed using both name and numeric indexes, while the latter can only be accessed using numeric indexes (of course NodeList is also an "array-like object")
Found through experiments elems can be indexed by name and array. Conclusion: What is returned by document.getElementsByTagName("p") in chrome is an HTMLCollection
HTMLCollection can get its length through elems.length, and its length can be obtained through elems[ 0] Does this way of accessing the elements
look like the access method of an array? In fact, it is just an "Array-like object", but it is not a native array of js, so the native methods of array cannot be accessed, such as (.pop() and .reverse())
The native JS array arr is obtained through jQuery.makeArray(elems) conversion, and then you can use the native method of array!
Convert jQuery-wrapped array into native Array
In addition to HTMLCollection, what else can be converted? Have you ever heard of jQuery wrapped arrays?
But I must have come across it. For example, you can get a group of p through $('p'). This group of p is an array wrapped in jQuery.
Another example, through .map( )The function also gets an array wrapped by jQuery. You can also get the length by length and access it through the subscript index. And the array wrapped by jQuery can also use the methods provided by jQuery.
Can be converted into a native Array through $.makeArray(obj). For example, the most common method is to obtain the jQuery array in the .map() function and then convert it into a native array and then obtain the result through join()
Of course, there is more than one way to convert an array wrapped by jQuery into a native array. Common ones include .get() and .toArray()
Convert json objects into native Array
This situation is a little more complicated, because the json object is not an "array-like object", so we need a conversion
Remember the several "array-like objects" we talked about before? They can all get the length through .length and can be accessed through subscript index, such as: fakeArr.length, fakeArr[0]
So can we change it by letting json support this method? What about "array-like object"?
Design it first:
To make json support fakeArr.length, it’s simple. You only need to define a key-value pair with the key as length
It seems that supporting subscript access can also be solved easily. In addition, key-value pairs can use numbers as keys~
Then try it:
var fakeArray = {0: "张三", 1: "李四", 2:"朱六", length:3}; var realArray = $.makeArray(fakeArray); console.log(fakeArray) console.log(realArray) realArray.reverse(); console.log(realArray);
see it? Success! The realArray here is already the native array of js, so you can use native methods such as reverse()
It should be noted that , length is very important during the conversion process, and this length is determined The length of the converted array
If the length in the above example is specified as 2, then the converted array will only have the first 2 elements, which is ["Zhang San", "李思"]
If the length in the above example is specified as 4, then the converted array will not be the array we want, but an array similar to new Array().push(fakeArray)
The above is the detailed content of Example analysis of how makeArray() in jQuery converts multiple types into JS native Array. For more information, please follow other related articles on the PHP Chinese website!

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.


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

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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