0

我想用简单的函数扩展所有数组的属性(这是我的作业)

Array.prototype.remove=(function(value){
var i;
var cleanedArray = new Array();
for(i= 0;i<this.length;i++)
{
    if(value !== this[i])
    {
        cleanedArray.push(this[i]);
    }
}

 this.length = cleanedArray.length;
 for(i=0;i<this.length;i++)
 {
     this[i] = cleanedArray[i];
 } })();

 var simpleArray = new Array(3,5,6,7,8,1,1,1,1,1,1,1);
 simpleArray.remove(1); console.log(simpleArray);

但是我在控制台中遇到错误,有人可以帮助我吗?

错误 :

Uncaught TypeError: Property 'remove' of object [object Array] is not a function 
4

1 回答 1

2

要声明一个函数,您不需要这些括号,也不需要调用它。

您可以将其声明为

  Array.prototype.remove=function(value){ // <== no opening parenthesis before function
     var i;
     var cleanedArray = new Array();
     for(i= 0;i<this.length;i++) {
        if(value !== this[i])
        {
            cleanedArray.push(this[i]);
        }
     }
     this.length = cleanedArray.length;
     for(i=0;i<this.length;i++) {
         this[i] = cleanedArray[i];
     } 
  }; // <== simply the end of the function declaration

看起来您对IIFE感到困惑,但您在这里不需要该构造。

如果您希望您的函数不可枚举,您可以使用Object.defineProperty来实现:

Object.defineProperty(Array.prototype, "remove", {
    enumerable: false, // not really necessary, that's implicitly false
    value: function(value) {
        var i;
         var cleanedArray = new Array();
         for(i= 0;i<this.length;i++) {
            if(value !== this[i])
            {
                cleanedArray.push(this[i]);
            }
         }
         this.length = cleanedArray.length;
         for(i=0;i<this.length;i++) {
             this[i] = cleanedArray[i];
         } 
    }
});

示范

于 2013-03-28T12:58:59.203 回答