简体   繁体   English

在Javascript中使用带有多个情况的switch语句时,如何引用情况?

[英]When using a switch statement in Javascript with multiple cases, how can I refer to a case?

So I have some code: 所以我有一些代码:

var Animal = 'Giraffe';
switch (Animal) {
  case 'Cow':
  case 'Giraffe':
  case 'Dog':
  case 'Pig':
    console.log('This animal will go on Noah\'s Ark.');
    break;
  case 'Dinosaur':
  default:
    console.log('This animal will not.');
}

Ideally, I'd like the first console.log to print "This Giraffe will go on Noah's Ark", or whatever the variable Animal happened to be. 理想情况下,我想要第一个console.log打印“这只长颈鹿将在诺亚方舟上”或任何可变的动物碰巧出现。 I want to refer to the case. 我想参考一下情况。 However, I'm not sure how to write that code. 但是,我不确定如何编写该代码。 Can someone help? 有人可以帮忙吗?

只需使用其他参数logAnimal

console.log('This', Animal, 'will go on Noah\'s Ark.');

You could use a token %s ( string in this case) and than after a comma use your variable: 您可以使用令牌 %s (在这种情况下为字符串 ),然后在逗号后使用变量:

 var Animal = 'Giraffe'; switch (Animal) { case 'Cow': case 'Giraffe': case 'Dog': case 'Pig': console.log('This %s will go on Noah\\'s Ark.', Animal); break; case 'Dinosaur': default: console.log('%s will not.', Animal); } 

Just use your variable: 只需使用您的变量:

var Animal = 'Giraffe';
switch (Animal) {
  case 'Cow':
  case 'Giraffe':
  case 'Dog':
  case 'Pig':
    console.log('This ' + Animal + ' will go on Noah\'s Ark.');
    break;
  case 'Dinosaur':
  default:
    console.log('This animal will not.');
}

(note: I'm using string concatenation here under the assumption that you may actually want to do something other than use the console.log function to do something like this - if you really just want to use console.log , it may be more reasonable to use one of the other answers provided) (注意:我在这里使用字符串连接的假设是,您实际上可能想做的事不是使用console.log函数来做类似的事情-如果您真的只想使用console.log ,那么可能会更多有理由使用提供的其他答案之一)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM