首页 技术 正文
技术 2022年11月11日
0 收藏 965 点赞 2,321 浏览 1605 个字

数组中foEach和map的用法详解

相同点:

1.都是循环遍历数组(仅仅是数组)中的每一项。

2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项value,当前项的索引index,原始数组array。

3.匿名函数中的this都是指Window。

4.IE6-8不兼容,通过在数组原型上扩展此方法可以实现

形式:

[].forEach(function(value,inede,array) {
//...
});
[].map(function(value,inede,array) {
//...
});Array.prototype.myForEach = function myForEach(callback,context){
context = context || window;
if('forEach' in Array.prototye) {
this.forEach(callback,context);
return;
}
//IE6-8下自己编写回调函数执行的逻辑
for(var i = 0,len = this.length; i < len;i++) {
callback && callback.call(context,this[i],i,this);
}
}

forEach():

参数:value数组中的当前项, index当前项的索引, array原始数组;

数组中有几项,那么传递进去的匿名回调函数就需要执行几次。

无返回值,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组;

    var data = [1,23,45,56,7,8];
data.forEach(function(value,index,arr) {
arr[index] = arr[index]*10;
});

map():

有返回值,可以return出来。

参数:value数组中的当前项,index当前项的索引,array原始数组;

区别:map的回调函数中支持return返回值;相当于把数组中的每一项改变(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);

    var data = [10,230,450,560,70,80];
var data1 = data.map(function(value,index,arr) {
return value/10;
});
console.log(data);
console.log(data1);
//(6) [10, 230, 450, 560, 70, 80]
//(6) [1, 23, 45, 56, 7, 8]

jQuery中的$.each和$.map

相比于原生js功能有了扩展,可以遍历对象。

形式:

$.each(obj,function(index,value) {
//...
});
$.map(obj,function(index,value) {
//...
});

$.each()

没有返回值。$.each()里面的匿名函数支持2个参数:当前项的索引i,数组中的当前项v。如果遍历的是对象,k 是键,v 是值。

$.each( { name: "assassin", age: 23 }, function(k, v){
console.log( "Key: " + k + ", Value: " + v );
});
/*
Key: name, Value: assassin
Key: age, Value: 23
*/

$.map()

有返回值,可以return 出来。$.map()里面的匿名函数支持2个参数和$.each()里的参数位置相反:数组中的当前项v,当前项的索引i。如果遍历的是对象,k 是键,v 是值。

    $.map( { name: "assassin", age: 23 }, function(k, v){
console.log( "Key: " + k + ", Value: " + v );
});
//Key: assassin, Value: name
//Key: 23, Value: age
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,110
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,584
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,202
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,837
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,920