Javascript:检查对象,如果[condition],则返回x

Javascript: Check through objects, if [condition], return x

本文关键字:返回 condition 如果 检查 对象 Javascript      更新时间:2023-12-19

我有三个对象,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);

我想创建一个函数,该函数可以确定哪个对象的z具有true值,而return具有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();

它有效。但我有一种迂回的感觉。有更好的方法来实现这一点吗?

我认为您的解决方案还可以,但您可以改进它:

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]);