【问题标题】:JavaScript, I can not understand switch parameterJavaScript,我无法理解开关参数
【发布时间】:2020-07-17 08:49:01
【问题描述】:

我最近开始学习 javascript 我目前正在 Udemy 观看 Javascript 课程。 虽然代码具有挑战性,但关于“开关”的参数我无法理解

let john = {
  fullName: 'John Smith',
  bills: [124, 48, 268, 180, 42],
  calcTips: function() {
    this.tips = [];
    this.finalValues = [];
    for (let i = 0; i < this.bills.length; i++) {
      let percentage;
      let bill = this.bills[i]

      switch (bill) { // If I put parameter as 'bill' variation, The result is only defalut.
        case bill < 50:
          percentage = 0.2;
          break;
        case bill >= 50 && bill < 200:
          percentage = 0.15;
          break;
        default:
          percentage = 0.1;
      }
      
      this.tips[i] = bill * percentage;
      this.finalValues[i] = bill + bill * percentage;
    }
  }
}

john.calcTips();

console.log(john);

然而

let john = {
  fullName: 'John Smith',
  bills: [124, 48, 268, 180, 42],
  calcTips: function() {
    this.tips = [];
    this.finalValues = [];
    for (let i = 0; i < this.bills.length; i++) {
      let percentage;
      let bill = this.bills[i]

      switch (true) { // If I put 'ture' as a parameter, It work's. Why?
        case bill < 50:
          percentage = 0.2;
          break;
        case bill >= 50 && bill < 200:
          percentage = 0.15;
          break;
        default:
          percentage = 0.1;
      }

      this.tips[i] = bill * percentage;
      this.finalValues[i] = bill + bill * percentage;
    }
  }
}

john.calcTips();

console.log(john);

我在谷歌上搜索过这个问题。 但我找不到解决这个问题的具体方法。 感谢您的帮助。

【问题讨论】:

标签: javascript switch-statement


【解决方案1】:

Switch 语句严格比较值。这意味着您可以比较 switch 变量的确切值。

switch (x) {

   case 1: console.log(1); break;

   case 2: console.log(2); break;

}

但是,如果你想让 switch 语句在这样的数字范围上工作,你可以做一个技巧:

var x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x < 9):
        alert("between 5 and 8");
        break;
    case (x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

该实现适用于布尔值的严格比较。 switch 语句用于true 并且将匹配true 的任何情况。

相关问题:Switch on ranges of integers in JavaScript

【讨论】:

  • 感谢您给我的建议
【解决方案2】:

switch 语句测试变量的值并将其与多个情况进行比较。一旦找到案例匹配,就会执行与该特定案例相关联的语句块。所以在这种情况下,你打开一个常量值。

更多细节: javascript: using a condition in switch case

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    相关资源
    最近更新 更多