简体   繁体   English

JavaScript条件检查数组长度

[英]Javascript condition to check array length

I have an array returned from server response, which has 3 possibilities, i need to check on UI; 我有一个从服务器响应返回的数组,它有3种可能,我需要检查UI;

  1. if length is 0..do something 如果长度是0 ..
  2. if length is 1...do something 如果长度是1 ...做点什么
  3. length > 1 ...do something 长度> 1 ...做某事

Is there a better way to write the below JS code, given the above conditions ? 在上述条件下,是否有更好的方法编写下面的JS代码?

if (myArray.length == 0) {

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

} else {

}

Well, you can always use switch : 好吧,您可以随时使用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 . 好处是,与if-elseif-else不同,switch表达式仅计算一次。

What you have is fine. 你所拥有的一切都很好。 Alternately, you could use switch : 或者,您可以使用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 . :-)它利用JavaScript强大的OR运算符来处理myArray.lengthdispatch中的任何条目都不匹配的情况。

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

                  case 1:
                   // do somthing   
                  break;

                  default:
                   // do somthing   
                  break ;
        }        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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