0

I want to extend the properties for all array with simple function (it's for my homework)

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);

but i get an error in console, can somebody help me ?

error :

Uncaught TypeError: Property 'remove' of object [object Array] is not a function 
2
  • 2
    Can you add the error to your question? Commented Mar 28, 2013 at 12:57
  • 1
    What is the error you get?? Pls put the output in SO. Commented Mar 28, 2013 at 12:58

1 Answer 1

2

To declare a function, you don't need those parenthesis and you don't need to call it.

You may declare it as

  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

It looks like you were confused with IIFE but you don't need that construct here.

If you want your function to be not enumerable, you may do it using 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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks but now i got another problem the remove functions is doing its work great,but my array has new element which is remove:function
If you want your function (which is a property) to be not enumerable, you may use Object.defineProperty. See edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.