扩展数组属性javascript

时间:2013-03-28 12:56:27

标签: javascript

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

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 

1 个答案:

答案 0 :(得分: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];
         } 
    }
});

Demonstration