共同点
(1)只能遍历数组
(2)都是循环遍历数组中的每一项
(3)每一次执行匿名函数都支持三个参数,数组中的当前项item,当前项的索引index,原始数组input
(4)匿名函数中的this都是指window
1.forEach
没有返回值
循环的特点是会自动省略为空的数组元素,相当于直接给我们筛空了。当是有时候也会给我们帮倒忙。
arr[].forEach(function(value,index,array){
xxxxx
})
· 数组中有几项,那么传递进去的匿名回调函数就需要执行几次
· 理论上这个方式是没有返回值的,只是遍历数组中的每一项,不对原来数组进行修改,但是可以自己通过数组的索引来修改原来的数组
var array = [10,34,57,43,76];
var res = array.forEach(function (item,index,input) {
input[index] = item*10;
})
console.log(res);//--> undefined;
console.log(array);//--> 通过数组索引改变了原数组;
[100,340,570,430,760]
2.map
有返回值,可以return出来
arr[].map(function(value,index,array){
xxx
return xxx
});
区别:map的回调函数中支持return返回值,return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆了一份,把克隆这一份的数组中的对应项改变了 );
var array = [10,34,57,43,76];
var res = array.map(function (item,index,input) {
return item*10;
})
console.log(res); [100, 340, 570, 430, 760]
console.log(array);不变 [10, 34, 57, 43, 76]
let arr=['jspang','技术胖','前端教程'];
console.log(arr.map(x=>'web'));
map在这里起到一个替换的作用
二、在jQuery中遍历
共同点:既可遍历数组,又可遍历对象
(1)$.each()
没有返回值,里面的匿名函数支持两个参数:当前项的索引i,数组中的当前项v,如果遍历的是对象,k是键,v是值
第一个和第二个参数正好和以上两个函数是相反的,注意不要记错了
$.each( ["a","b","c"], function(i, v){
alert( i + ": " + v );
});
$("span").each(function(i, v){
alert( i + ": " + v );
});
$.each( { name: "John", lang: "JS" }, function(k, v){
alert( "Name: " + k + ", Value: " + v );
});
(2)$.map()
有返回值,可以return出来
var arr=$.map( [0,1,2], function(v){
return v + 4;
});
console.log(arr);
$.map({"name":"Jim","age":17},function(k, v){
console.log( k+":"+v );
});