【发布时间】:2015-06-20 18:52:20
【问题描述】:
我正在尝试使用一种方法修改 Javascripts 数组类型,该方法仅在数组不存在时才会将值推送到数组。
这是我的代码:
// add a method conditionally
Array.prototype.method = function (name, func){
if(!this.prototype[name]){
this.prototype[name] = func;
return this;
}
};
// exclusive push
Array.method('xadd', function(value){
if(this.indexOf(value) === -1){
this.push(value)
};
return this;
});
但是,当我运行代码时,Firefox 中的暂存器会返回:
/*
Exception: TypeError: Array.method is not a function
@Scratchpad/3:19:1
*/
我想要一种普通的方式来做到这一点。不是库,因为我正在编写一个开源库。
【问题讨论】:
-
试试
[].method('xadd',... -
method是Array.prototype对象的一个方法。Array对象和prototype的实例具有该方法。
标签: javascript