简体   繁体   中英

Javascript condition to check array length

I have an array returned from server response, which has 3 possibilities, i need to check on UI;

  1. if length is 0..do something
  2. if length is 1...do something
  3. length > 1 ...do something

Is there a better way to write the below JS code, given the above conditions ?

if (myArray.length == 0) {

} else if (myArray.length == 1) {

} else {

}

Well, you can always use switch :

switch (myArray.length) {
  case 0:
    doSomething(); break;
  case 1:
    doSomethingElse(); break;
  default:
    doSomethingCompletelyDifferent();
}

The benefit is that switch expression will be calculated just once, unlike with if-elseif-else .

What you have is fine. Alternately, you could use switch :

switch (myArray.length) {
    case 0:
        // Empty
        break;
    case 1:
        // Has one entry
        break;
    default:
        // Has more than one entry
        break;
}

Or you sometimes see dispatch tables, but it's really mostly relevant when you're calling functions to start with:

var dispatch = {
    0: handleArrayEmpty,
    1: handleArrayOneEntry,
    multi: handleArrayMultipleEntries
};

(dispatch[myArray.length] || dispatch.multi)();

That's a bit out there, of course. :-) It makes use of JavaScript's curiously-powerful OR operator to handle the case where myArray.length didn't match any of the entries in dispatch .

switch (myArray.length) {
                  case 0:
                   // do somthing
                  break;

                  case 1:
                   // do somthing   
                  break;

                  default:
                   // do somthing   
                  break ;
        }        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM