5 ways to iterate arrays in JavaScript

Source: Internet
Author: User

Browser compatibility: ie9+

ES5 defines 5 iterative methods for an array. Each of these methods receives two parameters. The function to run on each item and (optionally) the scope object that runs the function--affects the value of this. where (optional) This parameter has not been encountered for the time being.

Where the function receives three parameters (each item in the array, the index value of each item, the array object itself).

The following is an introduction to the methods in 5:

Every (): Performs a function on each item in an array, and returns TRUE if each item returns TRUE.

Some (): Performs a function on each item in an array, and returns True if one of the items returns true.

Filter (): Performs a function on each item in the array, returning the item that returns true to an array.

ForEach () executes a function on each item in an array, with no return value. Similar to a For loop.

Map () Executes the function for each item in the array, returning (after processing) each item.

None of the above 5 methods will change the array itself.

Comparison of foreach and map:

    vararr = [1,2,3,4,5]; //every () filter () some () ForEach () map ()    varres = Arr.every (function(i,index,o) {returnI>2;    }); Console.log (arr); //[1,2,3,4,5]Console.log (RES);//false    varsome = Arr.some (function(i, K, l) {returnI>2;    }); Console.log (arr);//[1,2,3,4,5]Console.log (some);//true    varFilter = Arr.filter (function(i, K, l) {returnI>2;    }); Console.log (arr);//[1,2,3,4,5]Console.log (filter);//[3,4,5]    varForEach = Arr.foreach (function(i, K, l) {returnI>2;    }); Console.log (arr);//[1,2,3,4,5]Console.log (ForEach);//undefined    varMap = Arr.map (function(i, K, l) {returnI>2;    }); Console.log (arr);//[1,2,3,4,5]Console.log (map);//[False,false,true,true,true]

5 ways to iterate arrays in JavaScript

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.