挺容易
stringValue = numericValue >= 1000 ? numericValue.toString().substr(0, numericValue.toString().length - 3) + "TB" : numericValue >= 50? numericValue + "GB":"do here your 'below 50 stuff'";
基本上它是这样工作的:
(condition)?(return case true):(return case false);
所以你也可以嵌套它
(condition1)?(return case true1):((condition2)?(return case true2):(return case false both));
在您的情况下,您有 3 个案例。还有其他几种解决方案:经典if(){} else if(){} else{}
语句
switch: W3Schools JavaScript Switch 语句如下:
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
在您的情况下,我会考虑使用 switch 版本(更易于阅读)或 if、else if、else。嵌套三元运算符 ' ? : ' 不容易阅读。
对于开关,您可以执行以下操作
var numericValue = //a numeric value;
switch (true) {
case (numericValue <= 50):
//do case below 50
break;
case (numericValue > 50 && numericValue <= 1000):
//do case above 50 and below 1000
break;
default:
//do case above 1000
break;
}
Here we switch over the value 'true'. That means we look the different cases and check for the one that is 'true' (or default)