Home > Web Front-end > JS Tutorial > What are the traversal methods of arrays in js

What are the traversal methods of arrays in js

下次还敢
Release: 2024-05-06 11:06:17
Original
699 people have browsed it

There are many ways to traverse arrays in JavaScript: for loop forEach() method map() method filter() method find() method findIndex() method every() method some() method reduce() method

What are the traversal methods of arrays in js

Traversal methods of arrays in JS

In JavaScript, there are the following methods for traversing arrays:

1. for loop

const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
Copy after login

2. forEach() method

const arr = [1, 2, 3, 4, 5];

arr.forEach((element) => {
  console.log(element);
});
Copy after login

3. map() method

const arr = [1, 2, 3, 4, 5];

const newArr = arr.map((element) => element * 2);

console.log(newArr); // [2, 4, 6, 8, 10]
Copy after login

4. filter() method

const arr = [1, 2, 3, 4, 5];

const newArr = arr.filter((element) => element > 2);

console.log(newArr); // [3, 4, 5]
Copy after login

5. find() method

const arr = [1, 2, 3, 4, 5];

const element = arr.find((element) => element === 3);

console.log(element); // 3
Copy after login

6 . findIndex() method

const arr = [1, 2, 3, 4, 5];

const index = arr.findIndex((element) => element === 3);

console.log(index); // 2
Copy after login

7. every() method

const arr = [1, 2, 3, 4, 5];

const result = arr.every((element) => element > 0);

console.log(result); // true
Copy after login

8. some() method

const arr = [1, 2, 3, 4, 5];

const result = arr.some((element) => element > 3);

console.log(result); // true
Copy after login

9. reduce() method

const arr = [1, 2, 3, 4, 5];

const sum = arr.reduce((acc, element) => acc + element);

console.log(sum); // 15
Copy after login

The above is the detailed content of What are the traversal methods of arrays in js. For more information, please follow other related articles on the PHP Chinese website!

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