Reputation: 4914
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.
Upvotes: 0
Views: 94
Reputation: 4914
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
Upvotes: 1
Reputation: 48817
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.
Upvotes: 2