JavaScript 中遍历数组的方法有六种:for 循环、for...of 循环、forEach 方法、map 方法、filter 方法和 find 方法。每种方法都有各自的优点和缺点,可根据实际需要选择。
如何在 JavaScript 中遍历数组
遍历数组的方法:
JavaScript 中有几种方法可以遍历数组,每种方法都有其独特的优点和缺点:
1. for 循环
const arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); // 1, 2, 3, 4, 5 }
2. for...of 循环
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) => 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) => el * 2); console.log(doubledArr); // [2, 4, 6, 8, 10]
5. filter 方法
const arr = [1, 2, 3, 4, 5]; const evenArr = arr.filter((el) => el % 2 === 0); console.log(evenArr); // [2, 4]
6. find 方法
const arr = [1, 2, 3, 4, 5]; const firstEven = arr.find((el) => el % 2 === 0); console.log(firstEven); // 2
以上就是js如何遍历数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号