Home > Web Front-end > JS Tutorial > body text

Detailed examples of 5 iteration methods for JavaScript arrays

黄舟
Release: 2017-10-02 09:44:53
Original
1489 people have browsed it

This article mainly introduces the 5 iteration methods of JavaScript arrays in detail, which has certain reference value. Interested friends can refer to it

ES5 defines 5 iteration methods for arrays . Each method receives two parameters. The function to be run on each item and (optionally) the scope object to run the function on - affecting the value of this. //Among them (optional) this parameter has not been encountered yet.

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

The following is an introduction to the 5 methods:

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

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

filter(): Execute the function on each item in the array, and return the items that return true into an array.

forEach() executes the function on each item in the array and has no return value. Similar to a for loop.

map() Execute the function on each item in the array and return each (processed) item.

The above 5 methods will not change the array itself.

Comparison of forEach and map:


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

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

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

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

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

The above is the detailed content of Detailed examples of 5 iteration methods for JavaScript arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!