0

Here is what we have:

var MyObject = function(){
    var contents = [undefined,2,undefined,4,5];

    this.getContents = function(){
       return contents;
    }
}


var o = new MyObject();

As you understand, o.getContents() has the value of [undefined,2,undefined,4,5]

What I want to do is remove the undefined values of that private array, without overwriting the entire array, without making the private contents public, and without changing the objects code in general.

3
  • Your array contains only integers? Commented Jun 20, 2013 at 7:52
  • Just remove or also replace? Commented Jun 20, 2013 at 7:55
  • In that example yes, but the question is more generic. I discovered a way of modifying private properties of an object that are returned by a getter (similar to Javas myObject.getProperty().value = 10;) and wanted to share it. The reason I haven't accepted my answer, is because it is possible that someone has a better answer to this :) Commented Jun 20, 2013 at 7:55

2 Answers 2

2
return contents.filter(function(e) {return e});

This filter methods creates a new array while removing "", null, undefined and 0 values from the input array.

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

4 Comments

Isn't it more expensive to create an entire new array than making changes to the original one?
You could just do this: return contents.filter(Number), Tada!
@Loupax The problem with yours is that it changes the contents private variable content too, since you're passing a reference of it to your reindex function.
That was the entire point. I wanted to change the contents of the private property but without rewriting the object code, for whatever reason that prevents me from doing so. Perhaps I didn't phrase the question well enough...
1

Answering my own question, that was the approach I followed:

var MyObject = function(){
    var contents = [undefined,2,undefined,4,5];

    this.getContents = function(){
       return contents;
    }
}


   // Not extending the Array prototype is always a good idea
   var reIndex = function(){
   for(var i = 0; i < this.length; i++)
   {
       //Remove this element from the array
       if(this[i] === undefined){
          this.splice(i, 1);
       }
   }

}


var o = new MyObject();

console.log(o.getContents()); //[undefined, 2, undefined, 4, 5]

reIndex.call(o.getContents());

console.log(o.getContents()); //[2, 4, 5] 

Live example here

Comments

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.