我正在尝试使用一种方法修改 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
*/
我想要一个普通的方式来做到这一点。不是库,因为我正在编写一个开源库。
最佳答案
当您在 Array.prototype
上放置一个方法时,该方法将在 Array 的实例上可用。
// Add the custom method
Array.prototype.method = function() {
console.log('XXX');
}
var foo = [];
// prints XXX
foo.method();
关于javascript - 如何在 Javascript 中修改 Array.prototype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30957706/