关于各大前端框架对数组元素的遍历api设计

api的使用场景是针对数组进行遍历

1.先看看tangram思想的做法:

/*
*each-traverse all the element in array *
*@function*
*@param {Array} source---the array*
*@param {Function} iterator---it has two params(item,index)*
*@param {Object} thisObj---when the api is using, this pointer is what(default the source)*
*@remark(_ps:this api do not support the obj traverse)*
*@return {Array} the traversed array*
*/
ZYC.array.each = function(source,iterator,thisObj){
    var returnValue,item,i,_length = source.length;
    if('function' == typeof iterator){
	  for(i=0;i<_length;i++){
	     item = source[i];
		 //TODO--when thisObj is not defined we now use the source not the global object
		 returnValue = iterator.call(thisObj || source,item,i);
	     if(returnValue === false){
		    break;
		 }
	   }
	}
	return source;
};

2.如果你研究过prototype或者比较熟悉的话,我们来进一步看看它的做法。

Object.isFunction = function(obj){
   return typeof obj;
}


/*判断是否支持javascript1.6中新增的forEach
如果支持直接扔给_each
*/
if(Object.isFunction(Array.prototype.forEach)){
    Array.prototype._each = Array.prototype.forEach;
}

/*prototype里面还有一个Enumerable对象*/
var Enumerable = {
      each :function(iterator,context){
          var index =0;
          iterator = iterator.bind(context);
          try{
              this._each(function(value){
                 iterator(value,index++);
              })
          }catch(e){}
          return this;
        
      }
};


Object.extend(Array.prototype,Enumerable);

3.把kissy也加进来吧。

/*
KISSY.each([1,2,3],function(item,i){
	   debugger;
});
*/

each:function(object,fn,context){
    if(object){
        var key,
              val,
              i=0,
              length = object && object.length,
              isObj = length === undefined || S.type(object) === 'function';
    }
    context = context || host;
    
    if(isObj){
           //是对象
           for(key in object){
                if(fn.call(context,object[key],key,object) === FALSE){
                        break;
                }
           }
    }else{
           for(val = object[0];i<length && fn.call(context,val,i,object) !== FALSE;val = object[++i]){

           }
    }
    return object;
}

相关推荐