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 循环
系统共有:常规管理,公告管理,新闻管理,产品管理,采购订单管理,留言反馈管理,短信管理,用户管理,管理员管理,在线邮件管理,系统模板管理,图品缩略图及水印管理,Flash幻灯片管理,统计调查管理,系统数据调用管理,自定义扩展管理,语言标签库管理。18个主要功能模块组成。5月10号更新:1、全新双语模式设计开发2、多级动态JS菜单,支持在线添加,修改,删除3、新增单页管理模块,如扩展企业简介,联系方
0
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号