插件窝 干货文章 js如何遍历数组

js如何遍历数组

strong 方法 class const 272    来源:    2024-10-19
javascript 中遍历数组的方法有六种:for 循环、for...of 循环、foreach 方法、map 方法、filter 方法和 find 方法。每种方法都有各自的优点和缺点,可根据实际需要选择。

如何在 JavaScript 中遍历数组

遍历数组的方法:

JavaScript 中有几种方法可以遍历数组,每种方法都有其独特的优点和缺点:

1. for 循环

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

for (let i = 0; i <p><strong>2. for...of 循环</strong></p><pre class="brush:php;toolbar:false">const arr = [1, 2, 3, 4, 5];

for (const el of arr) {
  console.log(el); // 1, 2, 3, 4, 5
}

3. forEach 方法

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

arr.forEach((el, i) =&gt; console.log(el, i));
/*
  1 0
  2 1
  3 2
  4 3
  5 4
*/

4. map 方法

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

const doubledArr = arr.map((el) =&gt; el * 2);
console.log(doubledArr); // [2, 4, 6, 8, 10]

5. filter 方法

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

const evenArr = arr.filter((el) =&gt; el % 2 === 0);
console.log(evenArr); // [2, 4]

6. find 方法

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

const firstEven = arr.find((el) =&gt; el % 2 === 0);
console.log(firstEven); // 2
上一篇:如何加载js