Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 17:40:33
Original
973 people have browsed it

/**
* 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
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!