jQuery数组处理汇总

来源:互联网 发布:elona linux 编辑:程序博客网 时间:2024/05/22 03:23

有段时间没写什么了, 打算把jquery中的比较常用的数组处理方法汇总一下

$.each(array, [callback])遍历,很常用
1var arr = ['javascript', 'php', 'java', 'c++', 'c#', 'perl', 'vb', 'html', 'css', 'objective-c'];
2$.each(arr, function(key, val) {
3    // firebug console
4    console.log('index in arr:' + key + ", corresponding value:" + val);
5    // 如果想退出循环
6    // return false;
7});
$.grep(array, callback, [invert])过滤,常用
1var temp = [];
2temp = $.grep(arr, function(val, key) {
3    if(val.indexOf('c') != -1) 
4        return true;
5    // 如果[invert]参数不给或为false, $.grep只收集回调函数返回true的数组元素
6    // 反之[invert]参数为true, $.grep收集回调函数返回false的数组元素
7}, false);
8console.dir(temp);
$.map(array, [callback])用的不是太多
01//1.6之前的版本只支持数组
02temp = $.map(arr, function(val, key) {
03    //返回null,返回的数组长度减1
04    if(val === 'vb') return null;
05    return val;
06});
07console.dir(temp);
08//1.6开始支持json格式的object
09var obj = {key1: 'val1', key2: 'val2', key3: 'val3'};
10temp = $.map(obj, function(val, key) {
11    return val;
12});
13console.dir(temp);
$.inArray(val, array)判断是否在指定数组中,常用
1//返回元素在数组中的位置,0为起始位置,返回-1则未找到该元素
2console.log($.inArray('javascript', arr));
$.merge(first, second)合并两个数组,使用频率一般
1var frontEnd = ['javascript', 'css', 'html'],
2      backEnd = ['java', 'php', 'c++'];
3// 这种方式会修改第一个参数, 即frontEnd数组
4temp = $.merge(frontEnd, backEnd);
5console.dir(temp);
6console.dir(frontEnd);
7// 可以用下面的方式来避免对原数组的影响
8// $.merge($.merge([], frontEnd), backEnd);
$.unique(array)过滤数组中的重复元素,不常用
1<DIV>blahblahblah....</DIV>
2<DIV></DIV>
3<DIV class=dup></DIV>
4<DIV class=dup></DIV>
5<DIV class=dup></DIV>
6<DIV></DIV>
1// $.unique只支持DOM元素数组,去除重复DOM元素,不支持其他类型数组(String或者Number)
2// 获得原始的DOM数组,而不是jQuery封装的
3var divs = $('div').get(); 
4// 增加几个class为dup的div
5divs = divs.concat($('div.dup').get()); 
6console.log("before unique:" + divs.length);
7divs = $.unique(divs);
8console.log("after unique:" + divs.length);
$.makeArray(obj)将类数组对象转成数组,不常用
1//首先什么是类数组对象?jQuery官网上用divs = getElementsByTag('div')来做例子
2//这个divs有类似数组的一些方法比如length,通过[index]方式获取元素等
3//然后通过$.makeArray(divs)使它转为数组,就可以用数组的其他功能
4//比如reverse(), pop()等
$(dom).toArray()将jQuery集合恢复成DOM数组,不常用
1//跟makeArray一样,相当的不常用,一般情况可以忽略
原创粉丝点击