Maison  >  Article  >  interface Web  >  利用jQuery操作对象数组的实现代码_jquery

利用jQuery操作对象数组的实现代码_jquery

WBOY
WBOYoriginal
2016-05-16 18:07:19875parcourir

jQuery对于数组元素操作主要提供了以下工具:
(1)数组和对象的例遍:jQuery.each(obj,callback)
通用例遍方法,可用于例遍对象和数组。回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。如果需要退出 each 循环可使回调函数返回 false,其它返回值将被忽略。
(2)数组元素的过滤:jQuery.grep(array,callback,[invert])
使用过滤函数过滤数组元素。此函数至少传递两个参数:待过滤数组和过滤函数。过滤函数必须返回 true 以保留元素或 false 以删除元素。
(3)数组元素的查找:jQuery.inArray(value,array)
确定第一个参数在数组中的位置(如果没有找到则返回 -1 )。
(4)删除重复元素:jQuery.unique(array)
删除数组中重复元素。
下面的实例通过对象数组的过滤来实现获取或者删除指定属性为指定值的数组元素。

复制代码 代码如下:


<script> <BR>/** <BR>* 从对象数组中删除属性为objPropery,值为objValue元素的对象 <BR>* @param Array arrPerson 数组对象 <BR>* @param String objPropery 对象的属性 <BR>* @param String objPropery 对象的值 <BR>* @return Array 过滤后数组 <BR>*/ <BR>function remove(arrPerson,objPropery,objValue) <BR>{ <BR>return $.grep(arrPerson, function(cur,i){ <BR>return cur[objPropery]!=objValue; <BR>}); <BR>} <BR>/** <BR>* 从对象数组中获取属性为objPropery,值为objValue元素的对象 <BR>* @param Array arrPerson 数组对象 <BR>* @param String objPropery 对象的属性 <BR>* @param String objPropery 对象的值 <BR>* @return Array 过滤后的数组 <BR>*/ <BR>function get(arrPerson,objPropery,objValue) <BR>{ <BR>return $.grep(arrPerson, function(cur,i){ <BR>return cur[objPropery]==objValue; <BR>}); <BR>} <BR>/** <BR>* 显示对象数组信息 <BR>* @param String info 提示信息 <BR>* @param Array arrPerson 对象数组 <BR>*/ <BR>function showPersonInfo(info,arrPerson) <BR>{ <BR>$.each(arrPerson, function(index,callback){ <BR>info+="Person id:" + arrPerson[index].id + " name:" + arrPerson[index].name+ " sex:"+ arrPerson[index].sex+" age:"+ arrPerson[index].age+"\r\t"; <BR>}); <BR>alert(info); <BR>} <BR>//测试数据 <BR>var arrPerson=new Array(); <BR>var person=new Object(); <BR>person.id=1; <BR>person.name="帅哥"; <BR>person.sex="男"; <BR>person.age=30; <BR>arrPerson.push(person); <BR>person=new Object(); <BR>person.id=2; <BR>person.name="美眉甲"; <BR>person.sex="女"; <BR>person.age=28; <BR>arrPerson.push(person); <BR>person=new Object(); <BR>person.id=3; <BR>person.name="美眉乙"; <BR>person.sex="女"; <BR>person.age=20; <BR>arrPerson.push(person); <BR>//测试删除 <BR>showPersonInfo("原始数组: \t",arrPerson); <BR>arrPerson=remove(arrPerson,"id",1); <BR>showPersonInfo("删除之后: \t",arrPerson); <BR>//测试获取 <BR>arrPerson=get(arrPerson,"id",3); <BR>showPersonInfo("只获取ID为3的元素:\r\t",arrPerson); <BR></script>
Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn