原生JS forEach()和map()遍历的区别、兼容写法及jQuery $.each、$.map遍历操作
本文实例讲述了原生JSforEach()和map()遍历的区别、兼容写法及jQuery$.each、$.map遍历操作。分享给大家供大家参考,具体如下:
一、原生JSforEach()和map()遍历
共同点:
①.都是循环遍历数组中的每一项。
②.forEach()和map()里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。
③.匿名函数中的this都是指Window。
④.只能遍历数组。
1.forEach()
没有返回值。
varary=[12,23,24,42,1]; varres=ary.forEach(function(item,index,input){ input[index]=item*10; }) console.log(res);//-->undefined; console.log(ary);//-->会对原来的数组产生改变
2.map()
有返回值,可以return出来。
varary=[12,23,24,42,1]; varres=ary.map(function(item,index,input){ returnitem*10; }) console.log(res);//-->[120,230,240,420,10]; console.log(ary);//-->[12,23,24,42,1]
兼容写法:
不管是forEach还是map在IE6-8下都不兼容(不兼容的情况下在Array.prototype上没有这两个方法),那么需要我们自己封装一个都兼容的方法,代码如下:
/** *forEach遍历数组 *@paramcallback[function]回调函数; *@paramcontext[object]上下文; */ Array.prototype.myForEach=functionmyForEach(callback,context){ context=context||window; if('forEach'inArray.prototye){ this.forEach(callback,context); return; } //IE6-8下自己编写回调函数执行的逻辑 for(vari=0,len=this.length;i /** *map遍历数组 *@paramcallback[function]回调函数; *@paramcontext[object]上下文; */ Array.prototype.myMap=functionmyMap(callback,context){ context=context||window; if('map'inArray.prototye){ returnthis.map(callback,context); } //IE6-8下自己编写回调函数执行的逻辑 varnewAry=[]; for(vari=0,len=this.length;i二、jQuery$.each()和$.map()遍历
共同点:
即可遍历数组,又可遍历对象。
1.$.each()
没有返回值。$.each()里面的匿名函数支持2个参数:当前项的索引i,数组中的当前项n。如果遍历的是对象,k是键,n是值。
$.each(["a","b","c"],function(i,n){ alert(i+":"+n); });$("span").each(function(i,n){ alert(i+":"+n); });$.each({name:"John",lang:"JS"},function(k,n){ alert("Name:"+k+",Value:"+n); });2.$.map()
有返回值,可以return出来。$.map()里面的匿名函数支持2个参数和$.each()里的参数位置相反:数组中的当前项n,当前项的索引i。如果遍历的是对象,i是值,n是键。如果是$("span").map()形式,参数顺序和$.each() $("span").each()一样。
vararr=$.map([0,1,2],function(n){ returnn+4; }); console.log(arr);$.map({"name":"Jim","age":17},function(i,n){ console.log(i+":"+n); });感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。
PS:这里再为大家推荐一款JS数组遍历方式分析对比工具供大家参考:
在线JS常见遍历方式性能分析比较工具:http://tools.jb51.net/aideddesign/js_bianli
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数组操作技巧总结》、《JavaScript遍历算法与技巧总结》、《javascript面向对象入门教程》、《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。