Basic knowledge of javascript iteration method _

Source: Internet
Author: User
This article mainly introduces the relevant information about the javascript iteration method. if you need it, you can refer to the following five iteration methods to accept two parameters: the function to be run on each item and the scope of the function to be run (optional)

Every (): Run the given function for each item in the array. If the function returns true for each item, true is returned.
Filter (): Run the given function for each item in the array. Returns an array composed of true items.
ForEach (): Run the given function for each item in the array. This function does not return values.
Map (): Run the given function for each item in the array. Returns a function composed of the results of each function call.
Some (): Run the given function for each item in the array. Returns true if the function returns true for any item.

The code is as follows:


Var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
// Every () and some () are the most similar
// Every () item: current traversal item, index: current item index, array: array object itself
Var everyResult = numbers. every (function (item, index, array ){
Return item> 2;
});
Alert (everyResult); // false
// Some ()
Var someResult = numbers. some (function (item, index, array ){
Return item> 2;
});
Alert (someResult); // true
// Filter
Var filterResult = numbers. filter (function (item, index, array ){
Return item> 2;
});
Alert (filterResult); // [3, 4, 5, 4, 3]
// Map ()
Var mapResult = numbers. map (function (item, index, array ){
Return (item * 2 );
});
Alert (mapResult); // [2, 4, 6, 8, 10, 8, 6, 4, 2]
// There is no difference between forEach and for loop.
Var forEachResult = numbers. forEach (function (item, index, array ){
Alert (item)
});

The above is all the content of this article. I hope to give you some tips to better understand the javascript iteration method.

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.