Home > Article > Web Front-end > What are the traversal methods of arrays in js
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
Traversal methods of arrays in JS
In JavaScript, there are the following methods for traversing arrays:
1. for loop
<code class="javascript">const arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }</code>
2. forEach() method
<code class="javascript">const arr = [1, 2, 3, 4, 5]; arr.forEach((element) => { console.log(element); });</code>
3. map() method
<code class="javascript">const arr = [1, 2, 3, 4, 5]; const newArr = arr.map((element) => element * 2); console.log(newArr); // [2, 4, 6, 8, 10]</code>
4. filter() method
<code class="javascript">const arr = [1, 2, 3, 4, 5]; const newArr = arr.filter((element) => element > 2); console.log(newArr); // [3, 4, 5]</code>
5. find() method
<code class="javascript">const arr = [1, 2, 3, 4, 5]; const element = arr.find((element) => element === 3); console.log(element); // 3</code>
6 . findIndex() method
<code class="javascript">const arr = [1, 2, 3, 4, 5]; const index = arr.findIndex((element) => element === 3); console.log(index); // 2</code>
7. every() method
<code class="javascript">const arr = [1, 2, 3, 4, 5]; const result = arr.every((element) => element > 0); console.log(result); // true</code>
8. some() method
<code class="javascript">const arr = [1, 2, 3, 4, 5]; const result = arr.some((element) => element > 3); console.log(result); // true</code>
9. reduce() method
<code class="javascript">const arr = [1, 2, 3, 4, 5]; const sum = arr.reduce((acc, element) => acc + element); console.log(sum); // 15</code>
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!