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