循环遍历一个元素是开发中最常见的需求之一,那么让我们来看一个由框架BASE2和Jquery的结合版本吧.
01 |
var forEach = ( function (){ |
02 |
//数组与伪数组的遍历 |
03 |
var _Array_forEach = function (array, block, context) { |
04 |
if (array == null ) return ; |
05 |
//对String进行特殊处理 |
06 |
if ( typeof array == 'string' ){ |
07 |
array = array.split( '' ); |
08 |
} |
09 |
var i = 0,length = array.length; |
10 |
for (;i < length && block.call(context, array[i], (i+1), array)!== false ; i++) {} |
11 |
}; |
12 |
//对象的遍历 |
13 |
var _Function_forEach = function (object, block, context) { |
14 |
for ( var key in object) { |
15 |
//只遍历本地属性 |
16 |
if (object.hasOwnProperty(key)&&block.call(context, object[key], key, object)=== false ){ |
17 |
break ; |
18 |
} |
19 |
} |
20 |
}; |
21 |
return function (object, block, context){ |
22 |
if (object == null ) return ; |
23 |
if ( typeof object.length == "number" ) { |
24 |
_Array_forEach(object, block, context); |
25 |
} else { |
26 |
_Function_forEach(object, block, context); |
27 |
} |
28 |
}; |
29 |
})() |
函数本身并不复杂,但很精巧。加了一些简单的注释,想信大家能看懂。
来看一点例子
01 |
//1:1 \n 2:2 |
02 |
forEach([1,2,3,4,5], function (el,index){ |
03 |
if (index>2){ |
04 |
return false ; |
05 |
} |
06 |
alert(index+ ":" +el); |
07 |
}); |
08 |
09 |
function print(el,index){ |
10 |
alert(index+ ":" +el); |
11 |
} |
12 |
//a:a \n b:b \n c:c |
13 |
forEach({a: 'a' ,b: 'b' ,c: 'c' },print); |
14 |
15 |
//1:笨 \n 2:蛋 \n 3:的 \n 4:座 \n 5:右 \n 6:铭 |
16 |
forEach( "笨蛋的座右铭" ,print); |
17 |
|
18 |
function Person(name, age) { |
19 |
this .name = name || "" ; |
20 |
this .age = age || 0; |
21 |
}; |
22 |
Person.prototype = new Person; |
23 |
var fred = new Person( "笨蛋的座右铭" , 25); |
24 |
fred.language = "chinese" ; //极晚绑定 |
25 |
//name:jxl \n age:22 \n language:chinese |
26 |
forEach(fred,print); |
注:回调函数中的index参数下标从1开始
为什么不用内置的forEach
和getElementsByClassName一样,内置的forEach效率很高,但是在功能上有局限性,它无法在循环中途退出。而在我们这个forEach中,它可以在处理函数内通过返回false的方式退出循环,更加的灵活。
特别的length属性
length属性是一个很特别的属性,看到数组,大家一定会想到length,那看到带有length属性的对象呢?那大家一定要想到伪数组(类数组)。那什么是伪数组呢?简单的理解就是能通过Array.prototype.slice转换为真正的数组的带有length属性的对象。javascript最为著名的伪数组就是arguments对象。关于伪数组有很多东西,以后我会专门写一篇博文讲这个东西。大家只要记住:不要随便给对象赋予length属性,除非你明确的知道,你准备把它当作伪数组来使用。
本文转自艾伦 Aaron博客园博客,原文链接:http://www.cnblogs.com/aaronjs/archive/2011/09/05/2167535.html,如需转载请自行联系原作者