如何修改对象getter返回的私有变量?

时间:2013-06-20 07:46:32

标签: javascript oop

以下是我们的内容:

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,并且一般不更改对象代码。

2 个答案:

答案 0 :(得分:2)

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

filter方法会在从输入数组中删除""nullundefined0值时创建新数组。

答案 1 :(得分: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] 

实例here

相关问题