SoFunction
Updated on 2025-02-28

5 iterative methods for JavaScript arrays

ES5 defines 5 iterative methods for arrays. Each method receives two parameters. The function to run on each item and (optional) the scope object that runs the function -- affects the value of this. //The (optional) parameter has not been encountered yet.

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

Here is an introduction to the methods in 5:

every(): Execute a function on each item in the array. If each item returns true, the method returns true.

some():      Execute a function on each item in the array. As long as one item returns true, the method returns true.

filter():          Execute a function on each item in the array, and return the item that returns true, forming an array.

forEach()  Executes a function on each item in the array, no return value. Similar to a for loop.

map()        Execute a function on each item in the array, returning (processed) each item.

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

Comparison of forEach and map:

  var arr = [1,2,3,4,5];
  //every() filter() some() forEach() map()
  var res = (function(i,index,o){
    return i>2;
  });
  (arr); //[1,2,3,4,5]
  (res); //false

  var some = (function (i, k, l) {
    return i>2;
  });
  (arr);//[1,2,3,4,5]
  (some);//true

  var filter = (function (i, k, l) {
    return i>2;
  });
  (arr);//[1,2,3,4,5]
  (filter);//[3,4,5]

  var forEach = (function (i, k, l) {
    return i>2;
  });
  (arr);//[1,2,3,4,5]
  (forEach);//undefined

  var map = (function (i, k, l) {
    return i>2;
  });
  (arr);//[1,2,3,4,5]
  (map);//[false,false,true,true,true]

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.