想问下cloudgamer大牛的作品中经常出现的forEach,前面那个if有什么用?var forEach = function(array, callback, thisObject){
if(array.forEach){
array.forEach(callback, thisObject);
}else{
for (var i = 0, len = array.length; i < len; i++) { callback.call(thisObject, array[i], i, array); }
}
}
if(array.forEach){
array.forEach(callback, thisObject);
}else{
for (var i = 0, len = array.length; i < len; i++) { callback.call(thisObject, array[i], i, array); }
}
}
if()就是判断Array是否已经定义了forEach()方法
Object.prototype.forEach=function(items,func){
if(items){
for(temp in items){
if(typeof(items[temp])!="function"){
func(temp);
}
}
}
}
var arr = ['aa','bb','cc'];
arr.forEach(arr,function(item){
alert(item);
});
这是一个简单的带有Ruby风格的迭代实现,这种实现在很多js框架中有所体现如dojo,prototype