简体   繁体   中英

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. 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:

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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