Home Web Front-end JS Tutorial Introduction to the built-in methods of array objects in JavaScript_javascript skills

Introduction to the built-in methods of array objects in JavaScript_javascript skills

May 16, 2016 pm 05:40 PM

/**
* 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 < 2;
}); 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 < 999999; 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 < len; 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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

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

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

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 do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

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

See all articles