Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:检查对象,如果[condition],返回x_Javascript_Function_Object_Return - Fatal编程技术网

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

Javascript:检查对象,如果[condition],返回x,javascript,function,object,return,Javascript,Function,Object,Return,我有三个物体,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和return的y值 这就是我所拥有的: N.prototype.check = function(){ if(this.z == true){ r

我有三个物体,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
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]);
功能检查(对象){
//迭代所有对象
对于(var i=0;i
为什么不直接将对象插入数组中,并在数组中进行迭代以检查所需内容?您可能需要尝试代码复查堆栈交换。@davidbuzatto是的,这确实是个好主意。谢谢。@Inkbug很酷,我不知道它的存在。人们通常不应该在数组中使用
for
——一个正常的
for
循环就足够了。@Inkbug:我认为这只是口味的问题。他可能知道如何换一辆普通的车。我认为当你只需要迭代一个数组中的所有元素时,一个for in或一个for each是最好的选择。@DCoder:我真的不知道这一点。我将更改我的代码。完成。在阅读了您发送的帖子之后,我认为如果OP没有使用任何库,那么在本例中使用for..就可以了。