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 に答える