1

a、b、cの3つのオブジェクトがあります

function N(z, y){
   this.z = z;
   this.y = y;
}

var a = new N(true,0);
var b = new N(false, 1);
var c = new N(false, 2);

trueどのオブジェクトにその値zreturnその値があるかを判別できる関数を作成したいと思いyます。

これは私が持っているものです:

N.prototype.check = function(){
   if(this.z == true){
      return this.y;
   }    
}

function check(){
   var x;
   x = a.check();
   if(x !=undefined){
      return x;
   }
   x = b.check();
   if(x !=undefined){
      return x;
   }
   x = c.check();  
   if(x !=undefined){
      return x;
   }  
}

var x = check();

できます。でも、回り道をしているような気がします。これを達成するためのより良い方法はありますか?

4

1 に答える 1

0

あなたの解決策は大丈夫だと思いますが、あなたはそれを改善することができます:

function check( objects ) {
    // iterate over all objects
    for ( var i = 0; i < objects.length; i++ ) {

        // gets the result of the check method of the current object
        var result = objects[i].check();

        // if result exists (y is defined in the current object)
        if ( result ) {
            // returns it
            return result;
        }
    }

    // no valid results were found, so return null (or undefined)
    return null; // or undefined...
}

// checking 3 objects
var x = check([a, b, c]);
于 2012-07-22T04:56:12.487 に答える