NodeJS 带includes方法的JavaScript switch语句

zd287kbt  于 2023-06-29  发布在  Node.js
关注(0)|答案(2)|浏览(231)

好吧,有点奇怪,要么我在这里做的事情比我想象的要复杂一些,要么我的大脑不工作,但我试图使用switch语句来检查字符串是否包含某些内容,然后运行一段代码……

const msg = 'hash-test'

switch (msg) {

  case msg.includes('foo'):
    // do something
    break;

  case msg.includes('hash-'):
    // do something else
    break;

}

试图找出为什么我的msg.includes('hash-') case语句没有运行,因为我的字符串确实包含hash
有什么想法吗

stszievb

stszievb1#

switch(msg)将字符串msg与布尔值case msg.includes('foo')进行比较,后者永远不会严格相等。
所以:不要在这里使用switch语句!

const msg = 'hash-test'

if (msg.includes('foo')) {
    // do something
} else if (msg.includes('hash-')) {
    // do something else
}
js4nwp54

js4nwp542#

const msg = 'hash-test'

switch (msg.includes('foo') || msg.includes('hash-')) {
  case msg.includes('foo'):
    // do something
    console.log("heloo")
    break;
  case msg.includes('hash-'):
    // do something else
    console.log('world');
    break;
}

相关问题