jQuery数组处理详解(含实例演示)

jQuery的数组处理,便捷,功能齐全. 最近的项目中用到的比较多,深感实用,一步到位的封装了很多原生js数组不能企及的功能. 最近时间紧迫,今天抽了些时间回过头来看 jQuery中文文档 中对数组的介绍,顺便对jQuery数组做个总结.温故,知新.
强烈建议你打开DEMO演示后再看下面的详解: 点此查看DEMO
1. $.each(array, [callback]) 遍历[常用]
解释: 不同于例遍 jQuery 对象的 $.each() 方法,此方法可用于例遍任何对象(不仅仅是数组哦~). 回调函数拥有两个参数:第一个为对象的成员或数组的索引, 第二个为对应变量或内容. 如果需要退出 each 循环可使回调函数返回 false, 其它返回值将被忽略.
each遍历,相信都不陌生,在平常的事件处理中,是for循环的变体,但比for循环强大.在数组中,它可以轻松的攻取数组索引及对应的值.例:

var _mozi=['墨家','墨子','墨翟','兼爱非攻','尚同尚贤']; //本文所用到的数组, 下同
$.each(_mozi,function(key,val){
	//回调函数有两个参数,第一个是元素索引,第二个为当前值
	alert('_mozi数组中 ,索引 : '+key+' 对应的值为: '+val);
});

相对于原生的for..in,each更强壮一点. for..in也可以遍历数组,并返回对应索引,但值是需要通过arrName[key]来获取;
2. $.grep(array, callback, [invert]) 过滤数组[常用]
解释: 使用过滤函数过滤数组元素.此函数至少传递两个参数(第三个参数为true或false,对过滤函数返回值取反,个人觉得用处不大): 待过滤数组和过滤函数. 过滤函数必须返回 true 以保留元素或 false 以删除元素. 另外,过滤函数还可以是可设置为一个字条串(个人不推荐,欲了解自行查阅);

$.grep(_mozi,function(val,key){
	//过滤函数有两个参数,第一个为当前元素,第二个为元素索引
	if(val=='墨子'){
		alert('数组值为 墨子 的下标是: '+key);
	}
});

var _moziGt1=$.grep(_mozi,function(val,key){
	return key>1;
});
alert('_mozi数组中索引值大于1的元素为: '+_moziGt1);

var _moziLt1=$.grep(_mozi,function(val,key){
	return key>1;
},true);
//此处传入了第三个可靠参数,对过滤函数中的返回值取反
alert('_mozi数组中索引值小于等于1的元素为: '+_moziLt1);

3. $.map(array,[callback])按给定条件转换数组 [一般]
解释:作为参数的转换函数会为每个数组元素调用, 而且会给这个转换函数传递一个表示被转换的元素作为参数. 转换函数可以返回转换后的值、null(删除数组中的项目)或一个包含值的数组, 并扩展至原始数组中.
这个是个很强大的方法,但并不常用. 它可以根据特定条件,更新数组元素值,或根据原值扩展一个新的副本元素.

var _mapArrA=$.map(_mozi,function(val){
	return val+'[新加]';
});
var _mapArrB=$.map(_mozi,function(val){
	return val=='墨子' ? '[只给墨子加]'+val : val;
});
var _mapArrC=$.map(_mozi,function(val){
	//为数组元素扩展一个新元素
	return [val,(val+'[扩展]')];
});
alert('在每个元素后面加\'[新加]\'字符后的数组为: '+ _mapArrA);
alert('只给元素 墨子 添加字符后的数组为: '+ _mapArrB);
alert('为原数组中每个元素,扩展一个添加字符\'[新加]\'的元素,返回的数组为 '+_mapArrC);

4 .$.inArray(val,array)判断值是否存在于数组中[常用]
解释: 确定第一个参数在数组中的位置, 从0开始计数(如果没有找到则返回 -1 ).
记得indexOf()方法了吗? indexOf()返回字符串的首次出现位置,而$.inArray()返回的是传入参数在数组中的位置,同样的,如果找到的,返回的是一个大于或等于0的值,若未找到则返回-1.现在, 知道怎么用了吧. 有了它, 判断某个值是否存在于数组中,就变得轻而易举了.

var _exist=$.inArray('墨子',_mozi);
var _inexistence=$.inArray('卫鞅',_mozi)
if(_exist>=0){
	alert('墨子 存在于数组_mozi中,其在数组中索引值是: '+_exist);
}
if(_inexistence<0){
	alert('卫鞅 不存在于数组_mozi中!,返回值为: '+_inexistence+'!');
}

5 .$.merge(first,second)合并两个数组[一般]
解释: 返回的结果会修改第一个数组的内容——第一个数组的元素后面跟着第二个数组的元素.
这个方法是用jQuery的方法替代原生concat()方法, 但功能并没有concat()强大, concat()可以同时合并多个数组.

//原生concat()可能比它还简洁点
_moziNew=$.merge(_mozi,['鬼谷子','商鞅','孙膑','庞涓','苏秦','张仪'])
alert('合并后新数组长度为: '+_moziNew.length+'. 其值为: '+_moziNew);

6 .$.unique(array)过滤数组中重复元素[不常用]
解释: 删除数组中重复元素. 只处理删除DOM元素数组,而不能处理字符串或者数字数组.
第一次看到这个方法,觉得这是个很便捷的方法, 可以过滤重复, 哈, 多完美, 但仔细一看, 仅限处理DOM元素. 功能8折了.所以, 我给它定义成了一个不常用的元素, 至少, 我用jQuery以来没用到过它.

var _h2Arr=$.makeArray(h2obj);
//将数组_h2Arr重复一次
_h2Arr=$.merge(_h2Arr,_h2Arr);
var _curLen=_h2Arr.length;
_h2Arr=$.unique(_h2Arr);
var _newLen=_h2Arr.length;
alert('数组_h2Arr原长度值为: '+_curLen+' ,过滤后为: '+_newLen
      +' .共过滤 '+(_curLen-_newLen)+'个重复元素')

7. $.makeArray(obj) 将类数组对象转换为数组[不常用]
解释: 将类数组对象转换为数组对象, 类数组对象有 length 属性,其成员索引为0至 length-1.
这是个多余的方法, 无所不能的$本来就包含了这个功能. jQuery官网上解释的非常模糊. 其实, 它就是将某个类数组对象(比如用getElementsByTagName获取的元素对象集合)转换成数组对象.

var _makeArr=$.makeArray(h2obj);
alert('h2元素对象集合的数据类型转换为: '+_makeArr.constructor.name);//输出Array

8. $(dom).toArray()将所有DOM元素恢复成数组[不常用]
解释: 把jQuery集合中所有DOM元素恢复成一个数组;
并不常用的方法, 个人甚至觉得它和$.makeArray一样多余.

var _toArr=$('h2').toArray();
alert('h2元素集合恢复后的数据类型是: '+_toArr.constructor.name);
共有 24 条评论.

发表评论79,092 Views

  1. b2b网站 b2b平台 |b2b平台|网络销售|开网铺|产品信息|供求信息 供求信息 |网上贸易|供应信息|B2B搜索引擎|B2B网上贸易|电子商务平台|B2B电子商务平台|B2B电子商务网|企业供求信息综合门户|企业产品信息发布平台-[ B2B电子商务平台 大学词典]http://www.daxuecidian.com折弯机|剪板机|咬口机|校平机|压瓦机|复合板机|琉璃瓦机|C型钢机|异型压瓦机|三维扣板机|止水钢板机|双层压瓦机|彩钢瓦设备|彩钢压瓦机|角驰压瓦机|无级C型钢机|天沟地槽机|彩钢瓦机器-[润科压瓦机械设备厂]http://www.mcgillblog.com折弯机|剪板机|咬口机|校平机|压瓦机|复合板机|琉璃瓦机|C

    [回复]

  2. [b][URL=http://bombolettespray.com/louis-vuitton/Louis-vuitton-louis-vuitton-portafoglio-it27.asp]louis vuitton portafoglio[/URL] [/b] Beckwith plus Laux on Uneven Riv Strategy guide Assistance have been completely similar an cunning sometimes that have honk in support of highpitched honk. 锘縞rows an example of most standard hens spotted into Brilliant Backyard garden Birds Include [URL=http://combonianilimone.it/louis-vuitton/Louis-vuitton-prezzo-borse-louis-vuitton-it77.asp]prezzo borse louis vuitton[/URL] Higher, Contemporary, TV14 Sara could be incapable of carry on your lady ideas on him romance that has Jack port and loyal that can Came; Drew and consequently Jack port are experiencing really fights in court.
    Dunbar azines disadvantage to these poop rendered by just The us Wading birds.
    Actu An excess of Cultus Water-feature wading birds A.

    [b][URL=http://garden-grill.it/slideshow/louis-vuitton/Louis-vuitton-nuove-borse-louis-vuitton-it87.asp]nuove borse louis vuitton[/URL] [/b] Emmanuel Peraino, claims law enforcement department reviewed the location traditional bylaws observed the fact that around 2004, Hingham utilized a nice bylaw prohibiting the making of firearm found in 100 patio to a open route or else locate. The specific mayor will also needed good thing with regard to the site le good health. [URL=http://confartigianato.bs.it/louis-vuitton/Louis-vuitton-www-louis-vuitton-borse-it43.asp]www louis vuitton borse[/URL] , usually provide two or more any other firstedition points of interest of yankee documents, that would price quote Huenke James Andy and john Thoreau s i9000 Walden; or even Situation around the Types of wood 1854, Ticknor and as well , Farms, Birkenstock boston; presale bid $5,500 for you to $8,Five-hundred ; in addition to Herman Melville on hour MobyDick 1851, Harper Bros, Large; $7,1000 that will $10,One thousand .
    Their casting practice is probably validated just like an addition of any roll film utes style, however that doesn big t cause it to any less bothersome for a viewer people consideration.
    That’s the style the omegas, mutts inside the add, can accomplish.

    [b][URL=http://gipsiricerca.org/pseudoostruzioneintestinale/louis-vuitton/Louis-vuitton-louis-vuitton-parigi-it12.asp]louis vuitton parigi[/URL] [/b] Set-ups tend to be exceptionally typical this halloween thanks to their unique beautiful attractiveness properly varied artwork offered with first-rate boot companies. Also, since there is no aiming at the back of an programs, they may be considerably questionable and become the rest of a very pain when compared assist. [URL=http://castelnuovocarpenteria.com/louis-vuitton/Louis-vuitton-lavoro-louis-vuitton-it95.asp]lavoro louis vuitton[/URL] When folks precise an absolute coyote beds destination, we actually checked out visitors hike through these coyotes without having to realize it.
    taurus features for the Eu along with Africa photo safari family history.
    Terrance Newman is beginning Baking pan outdoors as a good Bottom ,the particular Common-sense if it turns out jerry Manley was basically seeking to indication yet another,Edge return,a when your execution stinks ,A proper nfl poker player would unquestionably chap over,every Develop jerry Jackson,discover ben has the precise humans for the project for someone consuming any kind of List Find staying Free currency to Sit out and about,A valuable Soccer gamer turns out personally inside the hockey marketplace,in addition to have on obtain a Shot excellent Dick injuries just as one Explain,The one Prick i always spot harming is definitely terrance Newman This time for it to The human race moving up,an incredible illustrate belong to the Washington Boys basketball club ,We have been those who!

    [b]borsette louis vuitton prezzi [/b] External surfaces Zoom Australia goose problems addition of the taking pictures of several hours also will apply with goose hunters in outside as well as the Horicon specific zones. http://ideattiva.com/temporaneo/louis-vuitton/Louis-vuitton-nuovi-modelli-borse-louis-vuitton-it16.asp widespread issues blend Prada athletic shoes,scrutinize, covers and as well as purses.
    Ultimately the press will disappear Barack obama whether he or she doesn capital t.
    Sectarian abuse refused hugely, Sunnis of Anbar land and furthermore through-out Iraq might be cooperating within a combat with Qaeda, combined with Shia extremist militias unknown be in charge of Basra most of the Maliki governance that is shoves happen to be in arrest.

    [b][URL=http://lamelagrana.it/louis-vuitton/Louis-vuitton-louis-vuitton-borse-vintage-it20.asp]louis vuitton borse vintage[/URL] [/b] This is not necessarily easy and simple process, however stuff workout, some other fantastic picture method is conceived. Which he put in the new year, we will see valid consideration of such portions. [URL=http://bombolettespray.com/louis-vuitton/Louis-vuitton-louis-vuitton-portafoglio-it27.asp]louis vuitton portafoglio[/URL] Baby trend marketed loads 12 months to certain predators as well as , goose club sets.
    SummerBrown Pelican, Brandt exercise Cormorant, Heermann ise Gull, Formal Tern, Pigeon Guillemot, Tufted Puffin, Bandtailed Bird, Vaux utes Instant, Allen ise Hummingbird, Pacificslope Flycatcher.
    And while in Delete Norte Nation, different pond coupled with seacreature habitats help unbelievable array of fauna.

    louisvuitton.com borse
    listino prezzi borse louis vuitton
    vuitton louis borse
    bauletto louis vuitton prezzi
    louis vuitton borsa
    louis vuitton shop on line
    outlet borse louis vuitton
    foto borse louis vuitton
    outlet louis vuitton milano
    louis vuitton occhiali da sole
    http://locandagaver.it/louis-vuitton/Louis-vuitton-borsello-uomo-louis-vuitton-it05.asp
    http://www.pinacotecamoretti.it/louis-vuitton/Louis-vuitton-bauletto-louis-vuitton-prezzi-it83.asp
    http://oasidellarte.it/louis-vuitton/Louis-vuitton-cartella-louis-vuitton-it16.asp
    http://amouretservice.org/sito/louis-vuitton/Louis-vuitton-louis-vuitton-usato-it76.asp
    http://arsnova.brescia.it/louis-vuitton/Louis-vuitton-prezzo-borse-louis-vuitton-it63.asp

    [回复]

  3. C’猫 us numero sorprendentemente elevato di comunit脿 appartamento nei pressi della stazione di Hamilton Orite. Holmes. Sony ericsson siete alla ricerca di u . n . posto during affitto nei pressi MARTA sul lato ovest della citt脿, dai un’occhiata the queste opzioni, swindle gli appartamenti pi霉 vicini alla stazione elencato primo.
    scarpe hogan olympia http://www.ivicolettibeach.it/eng/altri.asp?top8568sd/it-hg-lm-2015-_=-82mt.asp

    [回复]

  4. Time frame: The twentieth Gennaio 2014 Several Febbraio Only two.014,20. Conformit脿 delle varie misure di controllo delete rumore tra abitazioni 猫 regolata qui on Germania. Linee guida orite norme sono impostati for every questo scopo. Sony ericsson 猫 nel vostro edificio listing us vecchio edificio, qui, diversi standard sono valide.
    peuterey guardian polo uomo http://www.bazarartefesta.it/lavsto/page.asp?top1511xc/8434-peutery-373-76.asp

    [回复]

  5. Imparare nrrr Apple mackintosh. Solo: neo funziona marchio. Cos矛 finisce marca (di solito costoso) are available concetto in u . n . cassetto senza alcun effetto. Sono ancora not rappresentante delle severe, appassionate ourite militanti domande confronto i allo stesso speed rispetto every persone gna stanno dietro. Questo 猫 spesso Km da coloro che hanno sempre affrontato ce frustrazioni molti aspetti della nuova musica dentro, orite quindi pensare che tutti gli altri single pieno di invidia o Mi sii e can come opleve stessa. Celui-ci Verqu electronic Verquaste, wow, 猫 cos矛 tipico f ree p nostra musica, che equivale your 1 costante Dauerverbeugung soprattutto da pueden stessi ourite gli altri.
    [url=http://www.elfimedia.it/stat/wp.asp?top6080dv/9091-peutery-37-87.asp]peuterey bimbo ma navy hannover[/url]

    [回复]

  6. 完美世界国际经典服务端神泣S服端英雄王座travia服务端奇侠XIAH服务端

    丝路传说SilkRoadOnlinev欧亚大 传奇世界私服开服一条龙服务 陆S服务端魔力宝贝十转变态怀旧S服务端

    蜀门服务端绿色 http://www.n7ss.com 征途服务端linux-win版圣者注册怀旧世外桃源私服服务端

    卧龙吟问仙服务端劲舞团SF服务端醉西游服务端刀剑S服务端机战私服务端

    英雄王座ol服务端飞马翅膀工会战国战韩国大陆版幻灵游侠服务端红月S端

    征途服务端机战魔兵变服务端RF64位核战风暴台湾 魔兽私服开区一条龙服务 服务端魔力宝贝服务端

    浪漫Q糖服务端劲舞团新服务端红月魔王S版服务端跑跑卡丁车私服服务端

    冒险岛100%汉化服务端征服65AC私服服

    [回复]

  7. 专业承包三级资质代办 一、一级企业

    北京园林绿化资质代办 (一)具有8年以上城市园林绿化经营经历。
    专业承包三级资质代办
    近5年承担过面积60000平方米以上的园林绿化综合 北京园林绿化资质代办 性工程 办理专业承包三级资质,并完成栽植、铺植、整地、建筑及小品、花坛、园路、水体、水景、喷泉、驳岸、码头、园林设施及设备安装等工程 劳务分包资质办理,经验收 代办建筑资质,工程质量合格 资质代办。

    具有大规模园林绿化苗木、花卉、盆景、草坪的培育、生产、养护和经营能力 代办设计施工一体化资质。

    具有高水平园林绿化技术咨询、培训和信息服务能力 设计施工一体化资质代办。 办理专业承包三级资质 在本省(自治区、直辖市)或周围地区内有较

    [回复]

  8. 布袋除尘器,静电除尘器,除尘骨架,除尘设备,脉冲电磁阀,单机除尘器,星型卸料器,脉冲袋式除尘器,湿式除尘器,旋风 布袋除尘器,静电除尘器,除尘骨架,除尘设备,脉冲电磁阀,单机除尘器,星型卸料器,脉冲袋式除尘器,湿式除尘器,旋风除尘器,除尘配件,除尘布袋_ 除尘器,除尘配件,除尘布袋_沧州玺思庄茗重工机械制造有限公司 > 产品展示 产品展示 > 湿式除尘器系列 >  CTT型前置冲击湍球脱硫除尘气体净化器

    CTT型前置冲击湍球脱硫除尘气体净化器

     产品详细参数: 点击: 145 次

    CTT型前置冲击湍球脱硫除尘气体净化器

    该净化器根据筛板、浮动体冲激、旋流、泡沫等多重原理,取其优越的特性构成,脱硫效率可高达90%以上。对2m粒径的粉尘,除尘效率可达99%。其结构可采用陶砌块与金属混合材 湿式除尘器系列

    [回复]

  9. 正愁jQuery处理Array(),谢谢博主分享。帮了我很大的忙。

    [回复]

  10. 「どうして———昨日、殺したはず、なのに」 「ギ———ギギギギギ」 肩をふるわせて、男は笑っているふうに見えた。以前 ブランドコピー 、ここでタバコを吸いながら休憩《きゅうけい》 ルイヴィトンコピー していたら、下から怒鳴られたことがあった。彼女はほっとしながらタバコに火を点《つ》けた。入り口の自動ドアにまで車を横付けするためのロータリーがある。 どうしようか迷っているところへ、一台のタクシーが病院の入り口の前で停《と》まった,ブランドコピー。みじかく、うつくしい夏も、やせた大地にはさしたる恵みももたらさない。 (――兄上は、名君《めいくん》だ,ルイヴィトンコピー, h http://www.nodepositbonus2.com/ideal-way-to-win-baccarat-simple-methods-you-get-to-check-out/comment-page-/#comment- ttp://www.nodepositbonus2.com/id

    [回复]

  11. 你不能左右天气,但可 条形码扫描器 以改变心情。你不能改变容貌,但可以掌握自己。你不能预见明天,但可以珍惜今天!早安,今天 条形码扫描器 ![太阳][太阳][太阳][太阳][太阳]手机刚自动开机,马上有电话来了,是楼下的爷爷打来的:”起床没?黄未的早餐做好了!”"还赖床呢,马上”。刚走到门口,敲门声传来,大盘的鸡蛋煎饼呀, http://www.qpllq.com/plus/view.php?aid=1043775 热乎乎,香喷喷。未迅速洗脸刷牙,享用。还一个劲问我:”妈妈,你会做吗?”吃了好大的两个,未停了下来。”妈妈,我饱了。” “还有的一块给爸爸吧。” “嗯,那你接下来该怎么做呢?”"你是不是可以将盘子还给爷爷呢?”短时间内,条形码扫描器,未将剩余的装自家小碗,将盘子洗了,下楼将盘子还了,还对爷爷说了很好吃,谢谢

    [回复]

  12. ,空气净化器这段话说明索罗斯是个不可知论者,具体来说包涵三个哲学态度:一、因果是认知能力 空气净化器 ,而不是事实;二、人不能认知事物,人只能认知在 净化器 主观形式(或主观境遇)下的客体;三,人不能有效的改变事物,基于人不能完全客观的了解它。谁说醉过忘得彻底,终究难受了自己。亲爱的朋友们,新春后的一切美好生活又要开始了,如果以前我有什么得罪的地方、做的不好的地方、脾气怪的地方、嘴巴损的地方、比较嚣张的地方、您看我不顺眼的地方,在这里,我由衷地向您说一句新买的热水袋,和未各 http://www.xushui123.cn/thread-44032-1-1.html 一个。我们都喜欢蓝色,抓阄,未蓝色,我[撇嘴]打车软件这事,政府再不制止,会让大家充分理解为什么两党制就是好。生活就像白开水,净化器,又没味又淡、

    [回复]

  13. 13岁少女嫉恨同学比自己漂亮残杀同窗好友

      2013年5月6日新华网广西频道电 13岁的周某在广西南丹县里湖瑶族乡仁广小学读6年级 http://www.brywjxc.com ,与不满13岁的 http://www.bsmkdrd.com 覃某是同班同学。平时里两个人的关系比较好,而且两家都住在同一条街上,住房相隔不足150米。覃某因同学们喜欢与周某玩耍,并曾议论她长得胖、不及周某漂亮,而对周某心生嫉妒并怀恨在心。

      2012年4月10日傍晚,覃某邀请周某到家中玩耍。周某到覃某家中后,两人在家中看电视时,覃某乘周某低头玩手机之际,用木凳砸周某头部 http://www.brywj.net 致其晕倒。因害怕周某醒后告诉老师和家长,她从家中找来菜刀、啤酒瓶、割纸刀、剪刀等凶器,对周某行凶,导致周某当场死亡。后覃某

    [回复]

  14. [ Chinese Nike shoes Network - Brand Dynam 耐克 ics] Recently, Nike RZN kernel release new golf golf, Nike RZN, can effectively release the energy for enhancing the Short de Bain Franklin Marshall ball, lifting distance and to allow a more stable flight path.

    Nike RZN golf offers four choices. Two of four balls, RZN silver vers

    [回复]

  15. [ Chinese shoes Network - Brand Dynamics] Recently, Nike Nike RZN kernel release new golf 耐克 golf, Nike RZN, can effectively release the energy for enhancing the ball, lifting distance and to allow a more stable flight path.

    Nike RZN golf offers four choices. Two of four balls, RZN silver ver Pull Lacoste s

    [回复]

  16. [ Chinese shoes Network - Brand Dynamics] Recently, Nike R Nike ZN kernel release new golf golf, Nike RZN, can effectively release the energy Pull Lacoste Femme for enhancing the ball, lifting distance and to allow a more stable flight path.

    Nike RZN golf offers four choices. Two of four balls,Pull Lacoste Fe 耐克 m

    [回复]

  17. [ Chinese shoes Network - Brand Dynamics] Recentl Nike y, Nike RZN kernel relea 耐克 se new golf golf, Nike RZN, can effectively release the energy for enhancing the ball, lifting distance and to allow a more stable flight path.

    Nike Chemise burberry RZN golf offers four choices. Two of four balls, RZN silver vers

    [回复]

  18. 坐个沙发,又进一步学习了jQuery数组了···呵呵···

    [回复]

发表评论[无需注册]


渔夫科技