zoukankan      html  css  js  c++  java
  • jQuery数组处理汇总

    $.each(array, [callback])遍历,很常用
    var arr = ['javascript', 'php', 'java', 'c++', 'c#', 'perl', 'vb', 'html', 'css', 'objective-c'];
    $.each(arr, function(key, val) {
        // firebug console
        console.log('index in arr:' + key + ", corresponding value:" + val);
        // 如果想退出循环
        // return false;
    });

    $.grep(array, callback, [invert])过滤,常用

    var temp = [];
    temp = $.grep(arr, function(val, key) {
        if(val.indexOf('c') != -1)
            return true;
        // 如果[invert]参数不给或为false, $.grep只收集回调函数返回true的数组元素
        // 反之[invert]参数为true, $.grep收集回调函数返回false的数组元素
    }, false);
    console.dir(temp);

    $.map(array, [callback])用的不是太多

    //1.6之前的版本只支持数组
    temp = $.map(arr, function(val, key) {
        //返回null,返回的数组长度减1
        if(val === 'vb') return null;
        return val;
    });
    console.dir(temp);
    //1.6开始支持json格式的object
    var obj = {key1: 'val1', key2: 'val2', key3: 'val3'};
    temp = $.map(obj, function(val, key) {
        return val;
    });
    console.dir(temp);

    $.inArray(val, array)判断是否在指定数组中,常用

    //返回元素在数组中的位置,0为起始位置,返回-1则未找到该元素
    console.log($.inArray('javascript', arr));

    $.merge(first, second)合并两个数组,使用频率一般

    var frontEnd = ['javascript', 'css', 'html'],
          backEnd = ['java', 'php', 'c++'];
    // 这种方式会修改第一个参数, 即frontEnd数组
    temp = $.merge(frontEnd, backEnd);
    console.dir(temp);
    console.dir(frontEnd);
    // 可以用下面的方式来避免对原数组的影响
    //
     $.merge($.merge([], frontEnd), backEnd);

    $.unique(array)过滤数组中的重复元素,不常用

    // $.unique只支持DOM元素数组,去除重复DOM元素,不支持其他类型数组(String或者Number)
    //
     获得原始的DOM数组,而不是jQuery封装的
    var divs = $('div').get();
    // 增加几个class为dup的div
    divs = divs.concat($('div.dup').get());
    console.log("before unique:" + divs.length);
    divs = $.unique(divs);
    console.log("after unique:" + divs.length);

    $.makeArray(obj)将类数组对象转成数组,不常用

    //首先什么是类数组对象?jQuery官网上用divs = getElementsByTag('div')来做例子
    //
    这个divs有类似数组的一些方法比如length,通过[index]方式获取元素等
    //
    然后通过$.makeArray(divs)使它转为数组,就可以用数组的其他功能
    //
    比如reverse(), pop()等

    $(dom).toArray()将jQuery集合恢复成DOM数组,不常用

    //跟makeArray一样,相当的不常用,一般情况可以忽略

     

  • 相关阅读:
    记账本第二天
    记账本第一天
    HDU 1811
    Codeforces Round #246 (Div. 2) D. Prefixes and Suffixes
    KMP超强模板贴一份
    2014辽宁省赛总结
    Codeforces Round #244 (Div. 2)
    CodeForces 383D Antimatter
    NEU 1351 Goagain and xiaodao's romantic story I
    UVA 10692 Huge Mod
  • 原文地址:https://www.cnblogs.com/puke/p/2728448.html
Copyright © 2011-2022 走看看