Introduction to built-in methods of array objects in JavaScript _ javascript tips-js tutorial

Source: Internet
Author: User
You may have heard about the built-in methods of array objects. Today we will mainly introduce the built-in methods of array objects in JavaScript. If you are interested, refer to the following, hope to help you learn javascript /**
* This article simply sorts out the built-in methods of Array objects in W3C standards.
* No nutrition is provided in the full text. However, some questions are raised during the final performance test.
*/
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 pop and push, the array can be simulated into a stack for operation.
The data structure such as stack is characterized by "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 in the Array header, and return the length of the Array after the operation
You can use shift and unshift to perform queue operations.
The queue operation method is opposite to the stack, and the "First-In-First-Out" (FIFO, First-In-First-Out) is used ).
Splice

The Code is as follows:


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


Parameters:
Index: specifies where to add/delete elements.
How: specifies the number of elements to be deleted.
Elements: Specifies the new element to be added to the array. It is inserted at the subscript indicated by index.
The splice method is a supplement to pop, push, shift, and unshift.
The returned value is the deleted element.
Reverse

The Code is as follows:


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


Sort

The Code is as follows:


Array. sort ([compareFunction]);


If no parameters are used when you call this method, the elements in the array are sorted alphabetically.
To be more precise, sort by character encoding.
If you want to sort by other criteria, you need to provide a comparison function that compares two values and returns a number indicating the relative sequence of the two values. The comparison function should have two parameters, a and B. The returned values are as follows:
• If a is less than B, a value smaller than 0 is returned if a appears before B in the sorted array.
• If a is equal to B, 0 is returned.
• If a is greater than B, a value greater than 0 is returned.
--------------------------------------------------------------------------------
Access Method (Accessor methods)
These methods only return the corresponding results without modifying the array itself.
Concat

The Code is as follows:


Array. concat (value1, value2,..., valueN); // link two or more arrays and return the merged Array


However, there is something to note:

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. The elements are separated by the specified separator.
The default Delimiter is comma (,), and the returned value is the merged string.
[1, 2, 3]. join (); // return ", 3" Array. join () method is actually a reverse operation of String. splite.
Slice

The Code is as follows:


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


ToString

The Code is as follows:


Array. toString (); // This will not be said. All JavaScript has the toString method.


IndexOf and lastIndexOf* [ECMAScript 5]

The Code is as follows:


Array. indexOf (searchElement [, fromIndex]); // search from the beginning
Array. lastIndexOf (searchElement [, fromIndex]); // start searching from the end.


SearchElement: the value to be searched.
FromIndex: Index, indicating where the search starts
--------------------------------------------------------------------------------
Iteration methods)
ForEach * [ECMAScript 5]

The Code is as follows:


Array. forEach (callback [, thisArg]); // traverses the Array from start to end and calls the specified function for each element in the Array.


Parameters:
Callback: The function called when the array is traversed.
ThisArg: Specify the callback scope.
In addition, callback calls three parameters:
Value: array element
Index: array index
Array: array itself

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

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]); // traverses the Array elements, calls the specified function, and returns all results in an Array.
Parameters:
Callback: The function called when the array is traversed.
ThisObject: Specify the callback Scope
Example:

The Code is as follows:


[1, 2, 3]. map (function (num) {// return [2, 3, 4]
Return num + 1;
});


Filter* [ECMAScript 5]

The Code is as follows:


Array. filter (callback [, thisObject]); // traverses the Array call method. elements that meet the condition (return true) will be added to the returned value Array.


Parameters:
Callback: The function called when the array is traversed.
ThisObject: Specify the callback Scope
Example:

The Code is as follows:


[1, 2, 3]. filter (function (num) {// return [1]
Return num <2;
});


Every and some* [ECMAScript 5]

The Code is as follows:


Array. every (callback [, thisObject]); // "and"
Array. some (callback [, thisObject]); // "or"


Parameters:
Callback: The function called when the array is traversed.
ThisObject: Specify the callback Scope
Every: If all elements call a function and return true, true is returned. Otherwise, false is returned.
Some: If all elements call a function and return false, the return value is false. Otherwise, the return value is true.
Once the return values of every and some are determined, the traversal will be stopped immediately.
Example:

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]

The Code is as follows:


Array. reduce (callback [, initialValue]); // use the specified method to combine Array elements, from low to high by index (from left to right)
Array. reduceRight (callback [, initialValue]); // use the specified method to combine Array elements, from high to low by index (from right to left)


Parameters:
Callback: The function called when the array is traversed.
InitialValue: The previusvalue that is passed in the first call to callback.
In addition, callback calls four parameters:
Previusvalue: cumulative operation result so far
CurrentValue: array element
Index: array index
Array: array itself
Example:
[1, 2, 3]. reduce (function (x, y) {// return 106
Return x + y;
},100 );
--------------------------------------------------------------------------------
Performance Testing
Test System: Windows 7
Test Browser: Chrome 26.0.1386.0

The Code is as follows:


Var arr = [];

For (var I = 0; I <999999; I ++ ){
Arr. push (I );
}


ForEach

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 three random test results (the specific results are related to the computer configuration. The smaller the result, the better the performance ):
Time_forEach Time_for
1421.000 ms 64.000 ms
1641.000 ms 63.000 ms
1525.000 ms 63.000 ms

As you can see, Chrome has not made any special optimization on forEach. Compared with directly using for loop traversal, there is still a big gap in performance.
Because forEach is an item of ECMAScript 5, the old browser does not support it.
However, MDN provides a backward compatible solution:

The Code is as follows:


If (! Array. prototype. forEach ){
Array. prototype. forEach = function (fn, scope ){
For (var I = 0, len = this. length; I <len; ++ I ){
Fn. call (scope, this [I], I, this );
}
}
}


What's outrageous is that the native forEach method is not as good as its own forEach!
Also, what about other Iteration Methods of the Array object?
Let's take a look at this Demo is basically clear: http://maplejan.sinaapp.com/demo/ArratMethod.html
In addition, we found an interesting situation.
If you run the JavaScript code of the Demo directly on the console, you will find a great difference in performance!
At this time, the for loop write method is used directly, and the performance will be worse.
For this question, in zhihu on the question address: http://www.zhihu.com/question/20837774
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.