0

这是我们所拥有的:

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

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


var o = new MyObject();

如您所知,o.getContents()具有[undefined,2,undefined,4,5]

我想要做的是删除该私有数组的未定义值,而不覆盖整个数组,不contents公开私有,并且一般不更改对象代码。

4

2 回答 2

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

filter方法创建一个新数组,同时从输入数组中删除、""和值。nullundefined0

于 2013-06-20T07:49:22.580 回答
1

回答我自己的问题,这是我遵循的方法:

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] 

现场示例在这里

于 2013-06-20T07:50:39.433 回答