The self-band methods of array objects in JavaScript introduce _javascript techniques

Source: Internet
Author: User
/**
* This article is simply a comb through the current standard of the array object of the band method.
* The full text does not have any nutrition, but the final performance test part, has thrown out some questions.
*/
Assignment Method (Mutator methods)
These methods directly modify the array itself
pop and push
Array.pop (); Deletes the last element of the array, returning the deleted element
Array.push (element1, ..., ELEMENTN); Inserts the 1-n element at the end of the array, returning the length of the array after the operation
With this pop and push, the array can be modeled as stacks (stack) to operate.
The characteristics of this data structure of the stack are "LIFO" (LIFO, last in first).
Shift and Unshift
Array.shift (); Deletes the first element of the array, returning the deleted element
Array.unshift (element1, ..., ELEMENTN); Inserts the 1-n element at the head of the array, returning the length of the array after the operation
The use of shift and unshift allows you to implement queues (queue) operations.
The queue operates in the opposite way to the stack, using "FIFO, First-in-first-out".
Splice
Copy Code code as follows:

Array.splice (index, howmany[, element1[, ...) [, ELEMENTN]]);
Array.splice (index);

Parameters:
Index: Specify where to add/remove elements from.
Howmany: Specify how many elements should be deleted.
Elements: Specify the new element to be added to the array, starting at the subscript indicated by index.
The splice method is a complement to POPs, push, shift, and unshift.
The return value is the element that was deleted.
Reverse
Copy Code code as follows:

Array.reverse (); Reverses the order of elements in an array and returns the array after the reverse sequence

Sort
Copy Code code as follows:

Array.Sort ([comparefunction]);

If you call the method without using parameters, the elements in the array are sorted alphabetically.
To be more precise, sorting is done in the order of character encoding.
If you want to sort by other criteria, you need to provide a comparison function that compares two values, and then returns a number that describes the relative order of the two values. The comparison function should have two parameters A and B, and the return value is as follows:
• If a is less than B, a value less than 0 is returned in the sorted array before a should appear in B.
• If a equals B, return 0.
• If a is greater than B, a value greater than 0 is returned.
--------------------------------------------------------------------------------
access Method (accessor methods)
These methods simply return the corresponding result without modifying the array itself
concat
Copy Code code as follows:

Array.concat (value1, value2, ..., Valuen); Link 2 or more arrays and return the merged array

But there is a need to pay attention to the place, with the following example to illustrate:
Copy Code code 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 the elements in the array into a string. Where the elements are delimited by the specified delimiter.
The default delimiter is a comma (,), and the return value is a merged string.
[1, 2, 3].join (); The return "1,2,3" Array.join () method is actually the reverse operation of String.splite ().
Slice
Copy Code code as follows:

Array.slice (begin[, end]); Returns the selected element in an array

toString
Copy Code code as follows:

Array.tostring (); This is not to say, all JavaScript have tostring this method

indexOf and LastIndexOf*[ecmascript 5]
Copy Code code as follows:

Array.indexof (searchelement[, Fromindex]); Search from the beginning
Array.lastindexof (searchelement[, Fromindex]); Start at the end

Searchelement: value to search for
Fromindex: Index, indicating where the search starts
--------------------------------------------------------------------------------
Iterative Method (iteration methods)
ForEach *[ecmascript 5]
Copy Code code as follows:

Array.foreach (callback[, Thisarg]); Iterates through an array and invokes the specified function for each element in the array

Parameters:
Callback: Functions that are called when traversing an array
Thisarg: Specifies the scope of the callback
In addition, callback will call three parameters:
Value: Array element
Index: Array indexes
Array: Arrays themselves
Copy Code code 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 is unable to break the traversal of an array by breaking.
Workaround: Use the Try method to throw the exception and terminate the traversal.
Copy Code code 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]); Iterates through the array elements, invokes the specified function, and returns all the results with an array
Parameters:
Callback: Functions that are called when traversing an array
Thisobject: Specifies the scope of the callback
Example:
Copy Code code as follows:

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

Filter*[ecmascript 5]
Copy Code code as follows:

Array.filter (callback[, Thisobject]); The element that iterates through the array invocation method and satisfies the condition (returns True) is added to the array of returned values

Parameters:
Callback: Functions that are called when traversing an array
Thisobject: Specifies the scope of the callback
Example:
Copy Code code as follows:

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

every and some*[ecmascript 5]
Copy Code code as follows:

Array.every (callback[, Thisobject]); and
Array.some (callback[, Thisobject]); Or

Parameters:
Callback: Functions that are called when traversing an array
Thisobject: Specifies the scope of the callback
Every: Returns True if all element call functions return True, otherwise all returns FALSE.
Some: when all element call functions return FALSE, the result returns false, otherwise all returns TRUE.
Once the return value of every and some is determined, the traversal is stopped immediately.
Example:
Copy Code code 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]
Copy Code code as follows:

Array.reduce (callback[, InitialValue]); Uses the specified method to group elements of an array, from low to high by index (left to right)
Array.reduceright (callback[, InitialValue]); Uses the specified method to combine array elements, from highest to lowest index (right to left)

Parameters:
Callback: Functions that are called when traversing an array
InitialValue: Incoming Previousvalue The first time the callback is called
In addition, callback will call four parameters:
Previousvalue: The cumulative result of operations so far
CurrentValue: Array elements
Index: Array indexes
Array: Arrays themselves
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 code as follows:

var arr = [];

for (var i = 0; i < 999999; i++) {
Arr.push (i);
}

ForEach
Copy Code code 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 is a random 3 test results (specific results related to computer configuration, the smaller the result is the better performance):
Time_foreach Time_for
1421.000ms 64.000ms
1641.000ms 63.000ms
1525.000ms 63.000ms

As you can see, Chrome does not specifically optimize foreach, and there is a big gap between performance and direct for loop traversal.
Because foreach is a ECMAScript 5 thing, older browsers do not support it.
But MDN has a backward-compatible solution:
Copy Code code 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);
}
}
}

Outrageous is that the original ForEach method, in performance, incredibly inferior to their own construction of the foreach!
and other array objects, other iterative methods?
Everyone look at this demo is basically clear: http://maplejan.sinaapp.com/demo/ArratMethod.html
In addition, an interesting situation was found.
If you run the demo JavaScript code directly in the console, you'll see a big difference in performance!
This time, the method that writes directly with for loop, performance is worse.
For this question, in the knowledge of the question, question address: http://www.zhihu.com/question/20837774

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.