max*_*son 5 javascript arrays jquery prototype jquery-plugins
我已将以下方法添加到Array原型中:
Array.prototype.foreach = function(func){
for(var i = 0; i < this.length; i++){
if(!func(this[i]) === false) break; //return false from func in order to break the loop
}
return this;
}
Run Code Online (Sandbox Code Playgroud)
在同一个文件中,在上面的代码之后,我有以下jQuery插件:
jQuery.fn.addClassForEvents = function(){
var that = this;
arguments.foreach(function(event){
that.bind(event[0], function(){
that.addClass(event[0]);
})
.bind(event[1], function(){
that.removeClass(event[0]);
});
});
return this;
}
Run Code Online (Sandbox Code Playgroud)
为了使用这个jQuery插件,我的代码看起来像:
$('div').addClassForEvents(['mouseenter', 'mouseleave']);
Run Code Online (Sandbox Code Playgroud)
但是,浏览器在jQuery插件的"arguments.foreach(...."行中抛出一个错误,简单地说明了
对象#没有方法'foreach'
然而,该foreach方法适用于我的代码的其他地方.为什么在这个jQuery插件中未定义?
它不起作用,因为参数不是数组.它是一个(类似数组的)参数对象.
您可以在现代浏览器中使用切片将其转换为数组(并在IE中实际循环).
var argArray = Array.prototype.slice.call(arguments)
Run Code Online (Sandbox Code Playgroud)