循环遍历一个元素是开发中最常见的需求之一,那么让我们来看一个由框架BASE2和Jquery的结合版本吧.
01 |
var forEach = ( function (){ |
03 |
var _Array_forEach = function (array, block, context) { |
04 |
if (array == null ) return ; |
06 |
if ( typeof array == 'string' ){ |
07 |
array = array.split( '' ); |
09 |
var i = 0,length = array.length; |
10 |
for (;i < length && block.call(context, array[i], (i+1), array)!== false ; i++) {} |
13 |
var _Function_forEach = function (object, block, context) { |
14 |
for ( var key in object) { |
16 |
if (object.hasOwnProperty(key)&&block.call(context, object[key], key, object)=== false ){ |
21 |
return function (object, block, context){ |
22 |
if (object == null ) return ; |
23 |
if ( typeof object.length == "number" ) { |
24 |
_Array_forEach(object, block, context); |
26 |
_Function_forEach(object, block, context); |
函数本身并不复杂,但很精巧。加了一些简单的注释,想信大家能看懂。
来看一点例子
02 |
forEach([1,2,3,4,5], function (el,index){ |
09 |
function print(el,index){ |
13 |
forEach({a: 'a' ,b: 'b' ,c: 'c' },print); |
16 |
forEach( "笨蛋的座右铭" ,print); |
18 |
function Person(name, age) { |
19 |
this .name = name || "" ; |
22 |
Person.prototype = new Person; |
23 |
var fred = new Person( "笨蛋的座右铭" , 25); |
24 |
fred.language = "chinese" ; |
注:回调函数中的index参数下标从1开始
为什么不用内置的forEach
和getElementsByClassName一样,内置的forEach效率很高,但是在功能上有局限性,它无法在循环中途退出。而在我们这个forEach中,它可以在处理函数内通过返回false的方式退出循环,更加的灵活。
特别的length属性
length属性是一个很特别的属性,看到数组,大家一定会想到length,那看到带有length属性的对象呢?那大家一定要想到伪数组(类数组)。那什么是伪数组呢?简单的理解就是能通过Array.prototype.slice转换为真正的数组的带有length属性的对象。javascript最为著名的伪数组就是arguments对象。关于伪数组有很多东西,以后我会专门写一篇博文讲这个东西。大家只要记住:不要随便给对象赋予length属性,除非你明确的知道,你准备把它当作伪数组来使用。
我想这个函数是一个简单javascript工具库中的必备函数,它是金字塔的根基,在它的基础上,进行再封装,可以让你的库更强大,更加美丽!