Some ES5 methods for manipulating arrays

Source: Internet
Author: User

A number of methods for manipulating arrays have been added to the ES5 specification and are hereby listed for use

1. Foreach Loop

A bit like the Each loop of jquery

[12,23,36,4,5].foreach (function (v,k) {

Console.log (v) Gets the element value, 12,23,36,4,5

Console.log (k) Gets the element subscript, 0,1,2,3,4

})

Easy to traverse various arrays without the help of a three-party library

2.filter Filter

Used to filter elements

var arr = [12,23,36,4,5].filter (function (x) {

Return x>10; At this point, elements greater than 10 are filtered and placed into a new array, and the array is returned after the function ends

});

Console.log (arr) get [12,23,36]

3.every Matching

Similar to the format of the filter above, but returns a bool value

Returns true if all elements in the array are filtered, otherwise false

4.some Matching

Relative to the every, as long as one element passes the filter and returns True, NONE returns False

5.reduce Combination

Combine elements within an array to perform related operations

For example, an array summation

var sum = [12,23,36,4,5].reduce (function (x, y) {

return x+y;

},0);

Final sum gets the sum in the array

Basically receive a function to return the corresponding combination operation, and then you can set the initial value of the return value, where the sum initial value is 0

Two more examples to help understand

Array quadrature

var ji = [12,23,36,4,5].reduce (function (x, y) {

return x*y;

},1);

Obviously, the default initial value is 1 instead of 0.

To find the maximum value

var max = [12,23,36,4,5].reduce (function (x, y) {

Return (x>y)? x:y;

});

The maximum value does not require an initial value, and returns the maximum value obtained after 22 comparison

6.reduceRight

and reduce usage are basically the same, the difference is that all operations are from right to left, and in certain priority situations there will be different

Some ES5 methods for manipulating arrays

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.