【问题标题】:JS: Switch case seemingly goes to defaultJS:Switch case 似乎默认了
【发布时间】:2022-11-17 00:57:06
【问题描述】:

我有一个非常简单的方法,它接收一个数字并根据范围返回一个文本。 就是这个:

getBoardLocation(num) {
    switch (num) {
        case (6 >= num >= 1):
            return 'bl';          
        case (12 >= num >= 7):
            return 'br';
        case (18 >= num >= 13):
            return 'tl'
        case (24 >= num >= 19):
            return 'tr';
        default:
            break;
    }
}

出于某种原因,尽管通过断点可以确定传递的参数确实是一个数字,并且确实在其中一种情况的范围内,但它只是转到默认情况,如在 devtools 中所见,如下所示:

我觉得我错过了一些非常愚蠢的事情,但我不知道是什么。

【问题讨论】:

  • 你是什​​么意思?

标签: javascript reactjs switch-statement


【解决方案1】:

你的开关有很多问题

尝试这个

const isBetween = (n, start, stop) => n >= start && n <= stop 

function getBoardLocation (num) {
    switch (true) {
        case isBetween(num, 1, 6):
            return 'bl';          
        case isBetween(num, 7, 12):
            return 'br';
        case isBetween(num, 13, 18):
            return 'tl'
        case isBetween(num, 19, 24):
            return 'tr';
        default:
           throw new Error(num + 'is not valid')
    }
}
[1, 9, 14, 21].forEach(n => console.log(n, getBoardLocation(n)))

另一种方法可能是使用某种配置对象

const config = [
 {min: 1, max: 6, value: 'bl'},
 {min: 7, max: 12, value: 'br'},
 {min: 13, max: 18, value: 'tl'},
 {min: 19, max: 24, value: 'tr'}
]

 function getBoardLocation (num) {
    const res =  config.find(({min, max}) => num >= min && num <= max)?.value 
    if(!res){
      throw new Error(num + 'is not valid')
    }
    return res
 }
 
[1, 9, 14, 21].forEach(n => console.log(n, getBoardLocation(n)))

【讨论】:

  • 为了真正让代码更合乎逻辑,只需去掉 switch / case,并放入更合乎逻辑的 if else..
【解决方案2】:

得知 JS switch 语句并不像您想象的那样工作,您会感到失望。

case 语句中提供的值必须确切地匹配 switch 语句中提供的值以匹配该特定案例。

在您的情况下,true/false 永远不会匹配提供的号码,因此您会陷入默认情况。

【讨论】:

    【解决方案3】:

    来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

    switch 语句评估一个表达式,将表达式的值与一系列 case 子句进行匹配,并在第一个具有匹配值的 case 子句之后执行语句,直到遇到 break 语句。如果没有 case 匹配表达式的值,将跳转到 switch 语句的默认子句。

    这意味着表达式 (num) 在您的示例中被评估为 1, 但案例中的表达式被评估为 true/false 和 1 !== true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-09
      • 2020-01-27
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多