zoukankan      html  css  js  c++  java
  • jquery操作数组对象

    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 src="js/jquery.js" ></script>

    <script>

    /**

    * 从对象数组中删除属性为objPropery,值为objValue元素的对象

    * @param Array arrPerson 数组对象

    * @param String objPropery 对象的属性

    * @param String objPropery 对象的值

    * @return Array 过滤后数组

    */

    function remove(arrPerson,objPropery,objValue)

    {

    return $.grep(arrPerson, function(cur,i){

    return cur[objPropery]!=objValue;

    });

    }

    /**

    * 从对象数组中获取属性为objPropery,值为objValue元素的对象

    * @param Array arrPerson 数组对象

    * @param String objPropery 对象的属性

    * @param String objPropery 对象的值

    * @return Array 过滤后的数组

    */

    function get(arrPerson,objPropery,objValue)

    {

    return $.grep(arrPerson, function(cur,i){

    return cur[objPropery]==objValue;

    });

    }

    /**

    * 显示对象数组信息

    * @param String info 提示信息

    * @param Array arrPerson 对象数组

    */

    function showPersonInfo(info,arrPerson)

    {

    $.each(arrPerson, function(index,callback){

    info+="Person id:" + arrPerson[index].id + " name:" + arrPerson[index].name+ " sex:"+ arrPerson[index].sex+" age:"+ arrPerson[index].age+" ";

    });

    alert(info);

    }

    //测试数据

    var arrPerson=new Array();

    var person=new Object();

    person.id=1;

    person.name="帅哥";

    person.sex="男";

    person.age=30;

    arrPerson.push(person);

    person=new Object();

    person.id=2;

    person.name="美眉甲";

    person.sex="女";

    person.age=28;

    arrPerson.push(person);

    person=new Object();

    person.id=3;

    person.name="美眉乙";

    person.sex="女";

    person.age=20;

    arrPerson.push(person);

    //测试删除

    showPersonInfo("原始数组: ",arrPerson);

    arrPerson=remove(arrPerson,"id",1);

    showPersonInfo("删除之后: ",arrPerson);

    //测试获取

    arrPerson=get(arrPerson,"id",3);

    showPersonInfo("只获取ID为3的元素: ",arrPerson);

    </script>

  • 相关阅读:
    IIS运行asp程序出现The requested resource is in use 和 安装.net 2.0 后运行2.0程序出现 Failed to access IIS metabase 错误的解决
    动态sql语句基本语法
    屏蔽浏览器关闭按钮及ALT+F4 快捷键
    [转]如何进行.NET高效开发
    HttpRuntime.Cache 与HttpContext.Current.Cache的疑问
    我搜集的关于工作流方面的技术文章
    [转]输入框自动完成,模仿IE的,支持FireFox
    javascript 的面向对象特性参考
    定义局部变量时,字符串不能超过8000的方法
    世联地产软件工程师笔试试题
  • 原文地址:https://www.cnblogs.com/ImNo1/p/4619144.html
Copyright © 2011-2022 走看看