An in-depth exploration of Javascript array methods_Basic knowledge
In JavaScript, arrays can be created using the Array constructor, or quickly created using [], which is also the preferred method. Array is the prototype inherited from Object, and it has no special return value for typeof, it only returns 'object'.
1. Array.prototype.slice method
The array's slice method is typically used to extract a slice from an array. However, it also has the ability to convert "array-like" objects (such as arguments and HTMLCollection) into real arrays.
var nodesArr = Array.prototype.slice.call(document.forms);
var argsArr = Array.prototype.slice.call(arguments);
I’m just curious why the array’s slice method has such a capability, and how is it implemented in the javascript engine? Does the sibling method of slice have such ability?
With curiosity, download Google’s V8 javascript engine source code locally. The download address of V8 source code: https://github.com/v8/v8.
Look for "Array.prototype.slice" in v8-master/src/array.js:
function ArraySlice(start, end) {
CHECK_OBJECT_COERCIBLE(this, "Array.prototype.slice");
...
var result = []; // This sentence is the key
if (end_i if (UseSparseVariant(array, len, IS_ARRAY(array), end_i - start_i)) {
...
SparseSlice(array, start_i, end_i - start_i, len, result);
} else {
SimpleSlice(array, start_i, end_i - start_i, len, result);
}
...
Return result;
Then I guessed that the SimpleSlice method should be used to call the "class array", and then searched for "SimpleSlice" in the source code, and found that the SimpleSlice method was also called in the Array.prototype.splice source code, and the result variable was also initialized to an empty array. However, if you want to use the splice method to convert the "array-like" into a real array, you must pass in the starting position parameter as 0, that is:
var nodesArr = Array.prototype.splice.call(document.forms, 0);
Because its implementation principle is to form a new array from the deleted array items. Interested children can take a look at the source code implementation of Array.prototype.splice.
In addition, slice can also clone an array:
var arr = [1, 2, 3];
var cloneArr = arr.slice(); // cloneArr: [1, 2, 3]
2. Array.prototype.push method
Arrays can be merged using the push method:
var arr1 = [1, 'str', {name: 'lang'}];
var arr2 = [2, 'ing'];
Array.prototype.push.apply(arr1, arr2);
// Return result: [1, "str", {name: 'lang'}, 2, "ing"]
3. Array.prototype.sort method
First enter the code:
var arr = ['1', '2', '10', '12'];
arr.sort();
// Return results: ["1", "10", "12", "2"]
The above results are usually not what we want, so how to sort by numerical value:
arr.sort(function(a, b) {
return a - b;
})
// Return results: ["1", "2", "10", "12"]
With the sorting comparator function, you can customize many comparators to achieve personalized sorting.
4. length attribute
The length attribute of the array is not read-only, which means it can also be written. For example, use the length attribute to truncate the array:
var arr = [1, 2, 3, 4];
arr.length = 2;
// arr: [1, 2]
arr.length = 0;
// arr: []
At the same time, if the length attribute is made larger, the length value of the array will increase, and undefined will be used as the new element to fill.
var arr = [];
arr.length = 3;
// arr: [undefined, undefined, undefined]
Okay, that’s all for today. It’s already early in the morning. I’ll append here if I find any new discoveries in the future.
Before, I didn’t have the habit of blogging. I was only used to putting my usual summaries in Youdao Cloud Notes. I didn’t expect that it takes a lot of thought to write out my opinions, because I have to consider how to express them so that others can better understand.
If there is any incorrect expression or misunderstanding, please help me correct it.
Also attached are some commonly used javascript array methods
concat() concatenates two or more arrays and returns the result.
join() puts all elements of the array into a string. Elements are separated by the specified delimiter.
pop() removes and returns the last element of the array
push() adds one or more elements to the end of the array and returns the new length.
reverse() reverses the order of elements in an array.
shift() deletes and returns the first element of the array
slice() returns selected elements from an existing array
sort() sorts the elements of the array
splice() removes elements and adds new elements to the array.
toSource() returns the source code of the object
toString() converts the array to a string and returns the result.
toLocaleString() converts the array to a local array and returns the result.
unshift() adds one or more elements to the beginning of the array and returns the new length.
valueOf() returns the original value of the array object

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.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.


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

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

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.

Dreamweaver Mac version
Visual web development tools
