Array methods in ECMAScript 5

Source: Internet
Author: User

1. ForEach ()

The ForEach () method iterates through the array and invokes the specified function for each element.

var Data=[1,2,3,4,5];var sum=0;data.foreach (functiion (value) {sum+=value})//accumulate each value on sum



2. Map ()

The map () method passes each element of the call to the expedited group to the specified function and returns an array that contains the return value of the function.

A=[1,2,3];b=a.map (function (x) {return x*x})



3. Filter ()

The array element returned by the filter () method is a subset of the called Array. Filter by literal meaning

a=[5,4,3,2,1]

Smallvalues=a.filter (function (x) {return x<3}) //[2,1]

Everyother=a.filter (function (x,i) {return i%2==0})//[5,3,1]


4, every () and some ()

The Every () and some () methods are logical judgments of arrays, where they are used to determine whether a specified function is applied to an array element, which returns TRUE or false.

A=[1,2,3,4,5]a.every (function (x) {return <10})//truea.every (function (x) {return x%2==0})//false


5. Reduce and Reduceright

The reduce and Reduceright methods combine array elements using the specified function to generate a single value. The second argument is an initial value passed to the function

var A=[1,2,3,4,5]var sum=a.reduce (function (x, y) {return x+y},0)//array sum is 1+2+3+4+5var product=a.reduce (function (x, y) { return x*y},1)//Array quadrature 1*2*3*4*5var max=a.reduce (function (x, y) {return (x>y)? X:y})//ask for maximum value


Reduceright () works the same way as reduce (), where it processes data from high to low, not from low to high, according to the array index.


5, IndexOf and LastIndexOf ()

IndexOf () and LastIndexOf () search the entire array for the element with the given value, returning the index of the first element found, or 1 if not found

This function does not have too much to introduce it ~















Array methods in ECMAScript 5

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.