[英]How can I modify private variable that is returned by an objects getter?
這是我們所擁有的:
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
,並且通常不更改對象代碼。
return contents.filter(function(e) {return e});
此filter
方法在從輸入數組中刪除""
, null
, undefined
和0
值的同時創建一個新數組。
在回答我自己的問題時,我遵循的方法是:
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]
這里的例子
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.