1

I have three objects, a,b and 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);

I want to create a function that can determine which object has a true value for its z and return its y value.

This is what I have:

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

It works. But I have this feeling that I'm taking a detour. Is there a better way to achieve this?

1 Answers1

0

I think your solution is ok, but you can improve it:

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]);
davidbuzatto
  • 9,207
  • 1
  • 43
  • 50
  • One usually shouldn't use `for in` on an array - a normal `for` loop should be enough. – Inkbug Jul 22 '12 at 04:58
  • @Inkbug: I think that's just a matter of taste. He probably knows how to change to a regular for ;). I think that when you just need to iterate over all elements os an array, a for in or a for each are the best choice. – davidbuzatto Jul 22 '12 at 05:00
  • 2
    [`for-in` is dangerous](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays). – DCoder Jul 22 '12 at 05:04
  • @DCoder: I really didn't know this. I will change my code. Done. After reading the post that you sent, I think that using for..in in this example is fine if the OP isn't using any library. – davidbuzatto Jul 22 '12 at 05:06