1

我有三个对象,a,b 和 c

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及其z值。returny

这就是我所拥有的:

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 回答