Home  >  Article  >  Web Front-end  >  A brief discussion on JavaScript iteration method_Basic knowledge

A brief discussion on JavaScript iteration method_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:18:471027browse

The five iteration methods all accept two parameters: the function to be run on each item and the scope in which to run the function (optional)

every(): Runs the given function on each item in the array. Returns true if the function returns true for each item.
Filter(): Runs the given function on each item in the array. Returns an array of items that this function will return true.
forEach(): Runs the given function on each item in the array. This function has no return value.
Map(): Runs the given function on each item in the array. Returns a function consisting of the results of each function call.
Some(): Runs the given function on each item in the array. If the function returns true for any item, then return true

Copy code The code is as follows:

var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
​​​​ //every() and some() are most similar
//every() item: current traversed 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]
​​​​ //forEach is essentially the same as the for loop
      var forEachResult=numbers.forEach(function(item,index,array){
alert(item)
        });

The above is the entire content of this article. I hope it can give you some tips to better understand the JavaScript iteration method.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn