JS --Hash/Array--(遍歷)each方法
Posted on 2010-07-20 10:37 幻海藍(lán)夢(mèng) 閱讀(4665) 評(píng)論(0) 編輯 收藏 所屬分類: JS原文:http://www.02web.com/hublog/article.asp?id=344
數(shù)組在平時(shí)越用越多,可惜它自身沒(méi)有一個(gè)遍歷的方法
下面這樣是最簡(jiǎn)單的一個(gè)簡(jiǎn)歷方法,直接設(shè)置數(shù)組對(duì)象的
JavaScript代碼
- Array.prototype.each?=? function (?callback ){??
- for (? var ?i?=?0?,j?=? this .length?;?i?<?j?;?i++?){??
- ????callback.call( this, this[i], i );??
- ????}?????
- ?}??
上面的可以這樣使用
JavaScript代碼
- //遍歷一個(gè)數(shù)組如果是它是數(shù)組,就把它乘以10再輸出 ??
- var ?testArray?=?[1,2, '我' , '不' ,3,5];??
- testArray.each( function( value ){??
- ????typeof?value?==?'number'???alert( value *10 ):null;??
- })??
改變一個(gè)數(shù)組的內(nèi)容
JavaScript代碼
- //遍歷每個(gè)元素并且在它的前面加上chinese ??
- var ?testArray?=?[1,2, '我' , '不' ,3,5];??
- ????testArray.each( function( value, index ){??
- ????????this[index]?=?'chinese'?+?value;??
- })??
- ??
- testArray.each( function( v ){??
- ????alert(v);??
- })??
如果是一個(gè)多維數(shù)組呢?不停地調(diào)each就行了,下面修改each方法
JavaScript代碼
- //首先引入一個(gè)isArray函數(shù),這個(gè)函數(shù)非常有用,必備~ ??
- isArray?=?function( arrayObj ){??
- ????return?arrayObj?&&??
- ???????typeof?arrayObj?===?'object'?&&??
- ???????typeof?arrayObj.length?===?'number'?&&??
- ???????typeof?arrayObj.splice?===?'function'???
- ????}??
- ??
- Array.prototype.each?=?function(?callback){??
- ??for(?var?i?=?0?,j?=?this.length?;?i?<?j?;?i++){???
-
???isArray(
this
[i]
)?
this
[i].each( callback ):?
???????callback.call( this, this[i], i );?? - ???}??????
- }??
下面可以試驗(yàn)一下
JavaScript代碼
- var ?testArray?=?[1,2,[ 'sdf' , '2sdf' ],[12313,[[34,45]]]];??
- testArray.each(function(v){??
- ????alert(v);?//輸出1,2,sdf,2sdf,12313,34,45??
- })??