


Introduction 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
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
Array. reverse(); // Reverse the order of elements in the array and return the reversed array
sort
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
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:
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
Array. slice(begin[, end]); // Return the selected element in the array
toString
Array. toString(); // I won’t talk about this anymore, all JavaScripts have toString method
indexOf and lastIndexOf *[ECMAScript 5]
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
Copy code
The code is as follows:
[1, 2].forEach(function(value, index, array) {
console.log(value, index, array);
Copy code
The code is as follows:
try {
[1,2,3] .forEach(function(val) {
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;
Copy code
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 < 2;
Copy code
Array.every(callback[, thisObject]); // "AND"
Array. some(callback[, thisObject]); // "or"
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)
array: the array itself
Example:
[1, 2, 3]. reduce(function(x, y) { // return 106
}, 100);
---------- -------------------------------------------------- --------------------
Performance test
Test system: Windows 7
Test browser: Chrome 26.0.1386.0
Copy code
The code is as follows:
var arr = [];
Copy code
function forEachTest() {
howTime("forEach", function() {
}
});
}
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 |
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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

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...

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.

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 in JavaScript? When processing data, we often encounter the need to have the same ID...

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.

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 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.

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. �...
