0

I'd like to know how to check an array that got several variables in it.. something like that. I can explain better with the code shown:

// Ignore the words in here, they are just there to explan.
var $array = [
  alpha = {
    name : $('.a'),
    date : $('.b'),
    street: $('.c')
  },
  beta = {
    name : $('.x'),
    date : $('.y'),
    street: $('.z')
  }      
];

/* So now I got this arrays.. withing an array? is that correct?
 * or what is this called?
 * and now I want to check each object's length, if its 0 -> return false and
 * throw out an error, if >= 1 go on and check the next. */

// Check if all needed elements for the toggle to work are existent 
$.each( $array, function(key, value) {
  if ( !value.length ) {
    alert("Could not find "+ '"' + value.selector +'"!')
    return false
  };
});
// Well obviously this doesnt work..

Thanks in advance!

1
  • 4
    you should probably do research and know an object from an array Commented Mar 3, 2012 at 12:35

1 Answer 1

1

You can loop over the names of properties of an object with a for (... in ...) loop:

/* since the array isn't a jQuery object, don't prefix the name with `$` */
var things = [
    /* array elements have integer, not string, indices. In any case, 
       "alpha = ..." is the wrong syntax to set properties. What it
       does is set a variable named "alpha".
     */
    {...},
    {...},
];

$.each(things, function(idx, item) {
  for (p in item) {
    if (! item[p].length) {
      /* alerts are disruptive; use other means of informing
         the user or developer.
       */
      //alert("Could not find "+ '"' + value.selector +'"!')
      return false;
    } /* blocks don't need semicolon separators */
  }
});

See also "For .. in loop?"

Sign up to request clarification or add additional context in comments.

3 Comments

what is the (p in item) here?
@MartinBroder: that's what the links are for.
Should probably also use hasOwnProperty in that loop: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.