jQuery学习03---map,each方法学习

来源:互联网 发布:mac制谱软件 编辑:程序博客网 时间:2024/05/18 02:26

map方法主要用于对数组进行遍历

<html><head><meta http-equiv="Content-Type" content="text/html;charset=GBK"><link rel="stylesheet" type="text/css" href="table.css"><title></title><script src="../jquery-1.8.2.js" type="text/javascript"></script><style type="text/css"></style><script type="text/javascript">/*map(callback)方法的使用将一组元素转换成其他数组(不论是否是元素数组)你可以用这个函数来建立一个列表,不论是值、属性还是CSS样式,或者其他特别形式。这都可以用'$.map()'来方便的建立。map方法可以实现对一个数组遍历,然后分别对每一个元素进行操作。最后返回一个数组*/var arr = [10,20,30,40];arr=$.map(arr,function(item){return item*2;});alert(arr);//------------------------------------------------------------------------//查看map的源代码来实现自己的myMap方法function myMap(arr,fn){var ret=[],value;for(var i=0,length = arr.length;i<length;i++){value = fn(arr[i],i);if(value!=null){ret[ret.length]=value;}}return ret;}var arr2=[10,20,30,40];arr2 = myMap(arr2,function(item,i){return item+i;});alert(arr2);//------------------------------------------------------------------------</script></head><body></body></html>


each方法可以用于对字典或数组的遍历

<html><head><meta http-equiv="Content-Type" content="text/html;charset=GBK"><link rel="stylesheet" type="text/css" href="table.css"><title></title><script src="../jquery-1.8.2.js" type="text/javascript"></script><style type="text/css"></style><script type="text/javascript">//关于this的使用function testThis1(){alert(this);//默认情况下this代表的是window对象}testThis1();function testThis2(arg0,arg1){alert(this);alert(this+":"+arg0+":"+arg1);}var a="abc";//call方法可以改变this的指向,第一个参数就是this的指向,所以上面的alert(this)会显示abc;//testThis2.call(a);testThis2.call(a,"haha","red");/*$.each();each方法是用来对字典和数组的遍历,然后得到每一个键值对,有以下三种用法,第三种常用*///定义一个字典var dic ={"name":"zs","age":18,"sex":"男"};//在function中传入两个值的情况$.each(dic,function(key,value){alert(key+":"+value);});//在function中传入一个值的情况$.each(dic,function(key){alert(key+"+"+dic[key]);});//在function中不传值的情况$.each(dic,function(){//this 在这里指的是字典中的值alert(this);});//定义一个数组var arr=[20,30,40,50];$.each(arr,function(key,value){alert(key+":"+value);});//最常用$.each(arr,function(){//直接得到值alert(this);});</script></head><body></body></html>


原创粉丝点击