短的,如果否则javascript

时间:2017-08-11 14:42:24

标签: javascript ternary-operator

我试图了解这段代码是如何工作的。我知道三元运算符是condition ? option1 : option2,但我不知道这在这种情况下是如何工作的。

constructor(minSupport: number, minConfidence: number, debugMode: boolean) {
            this.minSupport = minSupport ? minSupport === 0 ? 0 : minSupport : 0.15;
            this.minConfidence = minConfidence ? minConfidence === 0 ? 0 : minConfidence : 0.6;
            this.debugMode = debugMode || false;
        }

2 个答案:

答案 0 :(得分:3)

this.minSupport = minSupport ? minSupport === 0 ? 0 : minSupport : 0.15;

它实际上做了什么(遗弃了非工作的东西):

this.minSupport = minSupport || 0.15;

所以基本上,如果minSupport是0或者没有传递(也就是未定义),那么它将是0.15。

答案 1 :(得分:0)

以下是给定代码段的完整翻译

constructor(minSupport: number, minConfidence: number, debugMode: boolean) {
  this.minSupport = (() => {
    if (minSupport) { 
      if (minSupport === 0) {
        // Interpreter will never reach this point because if minSupport is 0, it would straight away go to return 0.15 statement.
        return 0; 
      } else {
        return minSupport;
      }
    } else {
      return 0.15;
    }
  })();

  this.minConfidence = (() => {
    if (minConfidence) { 
      if (minConfidence === 0) {
        // Interpreter will never reach this point because if minConfidence is 0, it would straight away go to return 0.6 statement.
        return 0;
      } else {
        return minConfidence;
      }
    } else {
      return 0.6;
    }
  })();

  this.debugMode = (() => {
    if (debugMode) {
      return debugMode;
    } else {
      return false;
    }
  })();
}

您共享的代码段似乎是过度检查0,这已经在之前的if中处理过了。您可能想要将代码重写为此。

constructor(minSupport: number, minConfidence: number, debugMode: boolean) {
  if (minSupport === 0 || minSupport) {
    this.minSupport = minSupport;
  } else {
    this.minSupport 0.15;
  }

  if (minConfidence === 0 || minConfidence) {
    this.minConfidence = minConfidence;
  } else {
    this.minConfidence = 0.15;
  }

  if (debugMode) {
    this.debugMode = debugMode;
  } else {
    this.debugMode = false;
  }
}