本文中以数组为例,对象与此方法相同。
一、forEach遍历数组
arr.forEach(function(value,index,array){
//do something
})
- 参数:value数组中的当前项,index当前项的索引,array原始数组;
- 数组中有几项,那么传递进去的匿名回调函数就需要执行几次;
- 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组
1 var arr=[1,2,3,4,5];
2 var res=arr.forEach(function(value,index,array){
3 array[index]=value*10;
4 })
5 console.log(res); //undefined
6 console.log(arr); //[10,20,30,40,50] //通过索引改变了原数组
二、map函数
arr.map(function(value,index,array){
//do something
})
- 参数:value数组中的当前项,index当前项的索引,array原始数组;
- 区别:map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
var arr=[1,2,3,4,5];
var res=arr.map(function(value,index,array){
return value*10;
});
console.log(res);//[10,20,30,40,50],返回的新数组
console.log(arr); //[1,2,3,4,5] 原数组未发生改变
三、each函数
$.each(arr,function(index,value){
// do something
})
- 参数:arr要遍历的数组,index当前项的索引,value数组中的当前项
- 第1个和第2个参数正好和以上两个函数是相反的,注意不要记错了
var arr=[10,20,30,40,50];
$.each(arr,function(index,item){
console.log(index);//[0,1,2,3,4]
console.log(item);//[10,20,30,40,50]
})