这是一个有 2 个条件的条件语句,我需要添加第三个条件

This is a conditional statement with 2 conditions, I need to add a 3rd

本文关键字:条件 三个 添加 一个 语句      更新时间:2023-09-26

首先,我不做JS,所以提前为菜鸟问题道歉。

就像标题说的,我有这样一句话:

stringValue = numericValue >= 1000 ? numericValue.toString().substr(0, numericValue.toString().length - 3) + "TB" : numericValue + "GB";

基本上,它的作用是如果值超过 1000,则附加"TB",低于 1000 时附加"GB"。 我需要第三个条件,如果它低于 50,它会完全删除文本。

我可以看到这就像一个 if/else 语句,但我无法完全解码它并弄清楚如何添加第三个条件。 提前感谢!

这意味着:

stringValue = function(numericValue) {
    if(thirdCondition) {
          return "something";
    }
    if(numericValue >= 1000) {
      return numericValue.toString().substr(0, numericValue.toString().length - 3) + "TB";
    }
    else {
      return numericValue + "GB";
    }
}

我不确定你的第三个条件是什么,但你明白了。

这应该有效:

 stringValue = numericValue >= 1000 ? numericValue.toString().substr(0, numericValue.toString().length - 3) + "TB" : (numericValue > 50 ? numericValue + "GB" : numericValue);

您可以从一点缩进中受益。像这样打破它使它更具可读性:

stringValue = 
    numericValue >= 1000 
        ? numericValue.toString().substr(0, numericValue.toString().length - 3) + "TB" 
        : numericValue + "GB";

现在,要添加另一个条件,比如 else 部分,你可以这样做:

stringValue = 
    numericValue >= 1000 
        ? numericValue.toString().substr(0, numericValue.toString().length - 3) + "TB" 
        : numericValue < 1
            ? "Negligible"
            : numericValue + "GB";
var x = 5;
var y = x > 1000 ? "big" : x > 50 ? "medium" : "small"

您可以链接三元运算符。

value = function(numericValue) {
  numString = numericValue.toString();
  length = numString.length -3;
  subString = numString.substr(0, length);
  if(numericValue<50) { return ""; }
  else if(numericValue< 1000) { return numString + "GB"; }
  else { return substring + "TB"; }
}

不要无缘无故地让你的代码过于复杂。保持简单,清楚地表明你打算做什么。这将防止您和将来维护代码的任何其他人头疼。

编辑 - 固定行"返回数字字符串 + "GB"。

很简单

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
}

在您的情况下,我会考虑使用开关版本(更易于阅读)或 if,否则如果,否则。嵌套三元运算符 ' ?: ' 不容易阅读。

对于交换机,您可以执行以下操作

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;
}

在这里,我们切换值"true"。这意味着我们查看不同的情况并检查"真实"(或默认)

的情况