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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

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

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

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.

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 to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

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

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

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.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

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 Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

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.

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