search
HomeWeb Front-endJS TutorialIntroduction to the built-in methods of array objects in JavaScript_javascript skills

/**
* This article is purely to sort out the built-in Methods of Array objects in the current W3C standard.
* The full text is not nutritious, but the final part of the performance test does raise some questions.
*/
Mutator methods
These methods directly modify the array itself
pop and push
Array.pop (); // Delete the last element of the array and return the deleted element
Array.push(element1, ..., elementN); // Insert 1-N elements at the end of the array and return the length of the array after the operation
Through this pop and push, the array can be simulated as a stack for operation.
The characteristic of the stack data structure is "last in, first out" (LIFO, Last In First Out).
shift and unshift
Array.shift(); // Delete the first element of the array and return the deleted element
Array.unshift(element1, ..., elementN) ; // Insert 1-N elements into the head of the array, and return the length of the array after the operation
Use shift and unshift to implement queue operations.
The operation mode of queue is opposite to that of stack, using "first-in-first-out" (FIFO, First-In-First-Out).
splice

Copy code The code is as follows:

Array. splice(index, howMany[, element1[, ...[, elementN]]]);
Array.splice(index);

Parameters:
index: Where to specify Add/remove elements.
howmany: Specifies how many elements should be deleted.
elements: Specifies new elements to be added to the array, starting from the subscript pointed to by index.
The splice method is a complement to pop, push, shift, and unshift.
The return value is the deleted element.
reverse
Copy code The code is as follows:

Array. reverse(); // Reverse the order of elements in the array and return the reversed array

sort
Copy the code The code is as follows:

Array.sort([compareFunction]);

If no parameters are used when calling this method, Will sort the elements in the array alphabetically.
To be more precise, it is sorted according to the order of character encoding.
If you want to sort by other criteria, you need to provide a comparison function, which compares two values ​​and returns a number that describes the relative order of the two values. The comparison function should have two parameters a and b, and its return value is as follows:
•If a is less than b, a should appear before b in the sorted array, then return a value less than 0.
•If a equals b, return 0.
•If a is greater than b, return a value greater than 0.
-------------------------------------------------- ----------------------------------
Accessor methods
These methods just return the corresponding results without modifying the array itself
concat
Copy code The code is as follows:

Array.concat(value1, value2, ..., valueN); // Link 2 or more arrays and return the merged array

But there is one thing that needs to be noted, which is illustrated by the following example:
Copy the code The code is as follows:

var arr = [1, 2, 3];
arr.concat(4, 5); // return [1, 2, 3, 4, 5]
arr.concat([ 4, 5]); // return [1, 2, 3, 4, 5]
arr.concat([4, 5], [6, 7]); // return [1, 2, 3, 4, 5, 6, 7]
arr.concat(4, [5, [6, 7]]); // return [1, 2, 3, 4, 5, [6, 7]]

join
string = Array.join(separator);
Put all elements in the array into a string. Among them, elements are separated by specified delimiters.
The default delimiter is comma (,), and the return value is the combined string.
[1, 2, 3].join(); // return "1,2,3"Array.join() method is actually the reverse operation of String.splite().
slice
Copy code The code is as follows:

Array. slice(begin[, end]); // Return the selected element in the array

toString
Copy code The code is as follows:

Array. toString(); // I won’t talk about this anymore, all JavaScripts have toString method

indexOf and lastIndexOf *[ECMAScript 5]
Copy code The code is as follows:

Array.indexOf(searchElement[, fromIndex]); // Search
Array from scratch .lastIndexOf(searchElement[, fromIndex]); // Search from the end

searchElement: the value to be searched
fromIndex: index, indicating where to start the search
---- -------------------------------------------------- --------------------------
Iteration methods
forEach *[ECMAScript 5] / / Traverse the array from beginning to end, and for each element in the array, call the specified function
array: array itself



Copy code


The code is as follows:


[1, 2].forEach(function(value, index, array) {
console.log(value, index, array);
}); // return // 1 0 [1, 2] // 2 1 [1, 2] Note: forEach cannot interrupt array traversal through break.
Solution: Use the try method to throw an exception and terminate the traversal.




Copy code


The code is as follows:


try {
[1,2,3] .forEach(function(val) {
console.log(val); throw(e) }); } catch(e) { console.log(e); }

map
*[ECMAScript 5]
Array.map(callback[, thisArg]); // Traverse the array elements, call the specified function, and Return all results as an array
Parameters:
callback: function called when traversing the array
thisObject: specify the scope of the callback
Example:


Copy code

The code is as follows:


[1, 2, 3].map(function(num) { // return [2, 3, 4]
return num 1;
}); filter *[ECMAScript 5]


Copy code

The code is as follows:
Array.filter(callback[, thisObject]); // Traverse the array and call the method. Elements that meet the conditions (return true) will be Add to the array of return values ​​

Copy code

The code is as follows:


[1, 2, 3].filter(function(num) { // return [1]
return num }); every and some *[ECMAScript 5]


Copy code

The code is as follows:
Array.every(callback[, thisObject]); // "AND"
Array. some(callback[, thisObject]); // "or"
Parameters: callback: the function called when traversing the array thisObject: specifies the scope of the callback every : When all elements call the function and return true, the result will return true, otherwise it will return false. some: When all elements call the function and return false, the result will return false, otherwise it will return true.
Once the return values ​​of every and some are determined, the traversal will stop immediately.
Example:



Copy code


The code is as follows:

[1, 2, 3]. every(function(num) { // return false
return num > 1;
});
[1, 2, 3] . some(function(num) { // return true
return num > 2;
});

reduce and reduceRight *[ECMAScript 5] / / Use the specified method to combine array elements, from low to high (from left to right)
Array.reduceRight(callback[, initialValue]); // Use the specified method to combine array elements, according to Index from high to low (right to left)
Parameters: callback: the function called when traversing the array initialValue: the previousValue passed in when the callback is called for the first time In addition, the callback will call four parameters: previousValue: the cumulative result of the operation so far
currentValue: array element
index: array index
array: the array itself
Example:
[1, 2, 3]. reduce(function(x, y) { // return 106
return x y;
}, 100);
---------- -------------------------------------------------- --------------------

Performance test

Test system: Windows 7
Test browser: Chrome 26.0.1386.0




Copy code

The code is as follows:

var arr = [];
for(var i = 0; i arr.push(i); } forEach




Copy code

The code is as follows:
function forEachTest() {
howTime("forEach", function() {
var num = 0; arr.forEach(function(val, key) { num = val; }); }); howTime("for" , function() { var num = 0;
for(var i = 0, len = arr.length; i num = arr[i];
}
});
}


The following are the results of 3 random tests (the specific results are related to the computer configuration, the smaller the result, the better the performance):

time_forEach

time_for
1421.000ms 64.000ms
1641.000ms 63.000ms
1525.000ms 63.000ms

As you can see, Chrome has not specifically optimized forEach. Compared with directly using for loop traversal, the performance is still better. A big gap.
Because forEach is an ECMAScript 5 thing, older browsers do not support it.
However, MDN has provided a backward compatible solution:


time_forEach time_for
1421.000ms  64.000ms 
1641.000ms  63.000ms 
1525.000ms  63.000ms 
Copy the code


The code is as follows:
}


What’s outrageous is that the native forEach Method, in terms of performance, is actually not as good as the forEach constructed by yourself!
Also, what about other iteration methods of other Array objects?
You will basically understand it after looking at this Demo: http://maplejan.sinaapp.com/demo/ArratMethod.html
In addition, I also discovered an interesting situation.
If you run the Demo JavaScript code directly on the console, you will find a big difference in performance!
At this time, the performance of writing directly using a for loop will be even worse.
Regarding this question, I asked it on Zhihu. The question address is: http://www.zhihu.com/question/20837774
Statement
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
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

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 of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

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.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

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.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

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's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

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: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

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.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

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.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool