JavaScript数组的5种迭代方法
作者:李柳成 时间:2024-04-22 22:17:42
ES5为数组定义了5个迭代方法。每种方法都接收两个参数。要在每一项上运行的函数和(可选的)运行该函数的作用域对象--影响this的值。//其中(可选的)这个参数暂时未遇到过。
其中,函数都接收三个参数(数组中的每一项、每一项的索引值、数组对象本身)。
下面是5中方法的介绍:
every() :对数组中的每一项执行函数,如果每一项都返回 true ,则该方法返回 true。
some(): 对数组中的每一项执行函数,只要有一项返回了 true ,则该方法返回 true。
filter(): 对数组中的每一项执行函数,把里面返回 true 的项,组成一个数组返回。
forEach() 对数组中的每一项执行函数,没有返回值。类似于for循环。
map() 对数组中的每一项执行函数,返回(处理后的)每一项。
以上5种方法,都不会改变数组本身。
forEach和map的比较:
var arr = [1,2,3,4,5];
//every() filter() some() forEach() map()
var res = arr.every(function(i,index,o){
return i>2;
});
console.log(arr); //[1,2,3,4,5]
console.log(res); //false
var some = arr.some(function (i, k, l) {
return i>2;
});
console.log(arr);//[1,2,3,4,5]
console.log(some);//true
var filter = arr.filter(function (i, k, l) {
return i>2;
});
console.log(arr);//[1,2,3,4,5]
console.log(filter);//[3,4,5]
var forEach = arr.forEach(function (i, k, l) {
return i>2;
});
console.log(arr);//[1,2,3,4,5]
console.log(forEach);//undefined
var map = arr.map(function (i, k, l) {
return i>2;
});
console.log(arr);//[1,2,3,4,5]
console.log(map);//[false,false,true,true,true]
来源:http://www.cnblogs.com/eeeeeeeee/p/7610951.html
标签:js,数组,迭代
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python API自动化框架总结
2022-08-25 15:37:44
![](https://img.aspxhome.com/file/2023/7/134527_0s.png)
laravel清除视图缓存的代码
2023-11-24 14:39:39
使用python-pptx操作PPT的示例详解
2022-06-01 21:49:20
![](https://img.aspxhome.com/file/2023/0/104840_0s.png)
丰富段落里的标签
2008-03-16 14:11:00
解决mysql数据库数据迁移达梦数据乱码问题
2024-01-27 07:40:12
![](https://img.aspxhome.com/file/2023/1/67071_0s.jpg)
js的Prototype属性解释及常用方法
2024-06-07 16:00:32
![](https://img.aspxhome.com/file/2023/4/122144_0s.gif)
js用typeof方法判断undefined类型
2024-04-19 09:53:43
python flask安装和命令详解
2022-07-25 10:42:10
在SQL Server中实现最短路径搜索的解决方法
2024-01-24 13:47:10
![](https://img.aspxhome.com/file/2023/0/127990_0s.png)
两行代码实现的QQ窗口抖动效果
2008-09-06 12:34:00
python-Web-flask-视图内容和模板知识点西宁街
2021-03-10 22:21:15
Jinja2过滤器的使用、控制语句示例详解
2023-01-30 19:02:00
![](https://img.aspxhome.com/file/2023/1/104911_0s.png)
perl文件包含(do,require,use)指令介绍
2023-05-29 04:33:08
python 获取sqlite3数据库的表名和表字段名的实例
2024-01-24 13:34:22
python密码学RSA算法及秘钥创建教程
2022-03-20 04:02:34
![](https://img.aspxhome.com/file/2023/3/97253_0s.jpg)
FrontPage2002简明教程七:HTML在FrontPage中的应用
2008-09-17 11:33:00
![](https://img.aspxhome.com/file/UploadPic/200810/17/20081017113624552s.jpg)
Go中time.RFC3339 时间格式化的实现
2024-02-07 21:24:55
php中Array2xml类实现数组转化成XML实例
2023-07-14 21:48:13
解决matplotlib库show()方法不显示图片的问题
2021-08-25 19:53:34
python小程序实现刷票功能详解
2022-08-23 06:17:22