JS数组遍历中for,for in,for of,map,forEach各自的使用方法与优缺点
作者:wdc 时间:2024-05-02 16:15:45
JS数组遍历普通函数
优点:支持流程控制(break、continue、return)
for
const arr = ["A", "B", "C"]
for(let i = 0; i<arr.length; i++){
console.log(arr[i])
}
优点:能够对索引精确控制
缺点:语法较为繁琐
for in
const arr = ["A","B","C"]
arr["3"] = 1
Array.prototype["cc"] = "ck"
for(let e in arr){
console.log(arr[e])
}
缺点:
1.遍历索引为字符串,即e类型为字符串
2.会遍历可枚举的非数字类型键以及原型上的键
3.不同浏览器对for in 顺序实现可能不一致
for of
const arr = ["A","B","C"]
arr["3"] = 1
Array.prototype["cc"] = "ck"
for(let i of arr){
console.log(i)
}
优点:语法简洁、有序遍历
缺点:由于遍历的是值,对索引无直接控制
函数式编程-->高阶函数
缺点,不能进行流程控制
map
const arr = ["A","B","C"]
arr.map(e => console.log(e))
优点:语法简洁,返回一个旧数组的映射数组,不影响原数组
forEach
const arr = ["A","B","C"]
arr.forEach(e => console.log(e))
优点:语法简洁,在不需要返回数组时,性能较好比map好
名称 | 流程控制 | 函数式 |
---|---|---|
for | T | |
for of | T | |
forEach | T | |
map | T |
JS数组遍历函数总结:
在不需要流程控制时,优先使用map,不需要返回值使用forEach,需要索引的控制时,可以回退至for,for of一般结合内置默认迭代器的数据结构(Map、Set)使用,在需要结合生成器 async await 异步迭代时的选择
来源:https://www.cnblogs.com/sefaultment/p/10413690.html
标签:JS,数组遍历
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Python学习之安装pandas
2021-04-30 19:35:33
![](https://img.aspxhome.com/file/2023/8/86378_0s.png)
python中的unittest框架实例详解
2023-01-27 06:13:41
Python使用pyautocad+openpyxl处理cad文件示例
2022-05-24 11:44:18
Python图像处理之几何变换
2021-05-05 12:46:39
![](https://img.aspxhome.com/file/2023/0/131560_0s.png)
python处理圆角图片、圆形图片的例子
2021-06-08 15:20:15
![](https://img.aspxhome.com/file/2023/6/92356_0s.png)
JS实现利用两个队列表示一个栈的方法
2024-02-26 12:41:03
![](https://img.aspxhome.com/file/2023/4/56534_0s.jpg)
SQL Server 2005五个动态管理对象
2009-02-24 17:41:00
Vue + Webpack + Vue-loader学习教程之相关配置篇
2024-04-29 13:10:40
Sql Server、Oracle以及Access数据库 判断字段是否为空的办法 (From calmzeal's code life)
2011-02-24 19:44:00
解决selenium+Headless Chrome实现不弹出浏览器自动化登录的问题
2022-01-14 12:27:24
![](https://img.aspxhome.com/file/2023/8/117518_0s.png)
Python如何使用Gitlab API实现批量的合并分支
2023-01-31 18:17:45
Python字典底层实现原理详解
2021-04-09 12:58:28
python爬虫之urllib库常用方法用法总结大全
2023-12-25 21:55:52
用js实现用户输入密码的强度
2007-11-22 21:41:00
python处理列表的部分元素的实例详解
2021-04-16 01:13:05
Python在for循环中更改list值的方法【推荐】
2023-03-05 07:14:28
如何获知用户的IP?
2009-11-24 20:52:00
PyTorch两种安装方法
2022-04-16 04:11:50
![](https://img.aspxhome.com/file/2023/6/76166_0s.png)
python分割一个文本为多个文本的方法
2022-09-01 06:40:33
如何运用python读写CSV文件
2021-11-13 04:35:36
![](https://img.aspxhome.com/file/2023/4/97674_0s.png)