forEach与map异同 | 您所在的位置:网站首页 › foreach与map › forEach与map异同 |
一.原生js forEach()和map()遍历
共同点: 1.都是循环遍历数组中的每一项. 2.forEach()和map()里面每一次执行匿名函数都支持3个参数,数组中的当前项item,当前的index,原始数组arr. 3.匿名函数中的this都是指window. 4.只能遍历数组. 区别: 1.forEach() 没有返回值. var ary = [1,2,4,3]; var res = ary.forEach(function(item,index,arr){ input[index]=item*10; }) console.log(res);//undefined; console.log(ary);//会对原来的数组产生改变; 2.map 有返回值,可以return出来. var ary = [1,3,2,4]; var res = ary.forEach(function(item,index,arr){ return item*10; }) console.log(res);// [10,30,20,40]; console.log(ary);// [1,3,2,4]; 二.jquery $.each()和$.map()遍历 共同点: 即可遍历数组,又可遍历对象. 区别 1.$.each() 没有返回值。$.each()里面的匿名函数支持2个参数:当前项的索引i,数组中的当前项n。如果遍历的是对象,k 是键,n 是值。 $.each( ["a","b","c"], function(i, n){alert( i + ": " + n ); }); $.each( { name: "XiaoHong", lang: "vue" }, function(k, n){ alert( "Name: " + k + ", Value: " + n ); }); 2.$.map() 有返回值,可以return 出来。$.map()里面的匿名函数支持2个参数和$.each()里的参数位置相反:数组中的当前项n,当前项的索引i。如果遍历的是对象,i 是值,n 是键。如果是$("span").map()形式,参数顺序和$.each() $("span").each()一样。 var arr = $.map([0, 1, 2], function (n, i) {return i + 1;});console.log(arr); $.map({"name":"XiaoMing","age":18},function(i,n){ console.log(i+":"+n);});
|
CopyRight 2018-2019 实验室设备网 版权所有 |