Dom*_*rso 1 javascript switch-statement
我想知道在执行代码块时是否有可能在Javascript switch语句中使用类似于“ this”的东西。
例如:
switch(x) {
case 'The pyramids of Giza':
console.log(this);
break;
case 'The Leaning Tower of Pisa':
console.log(this);
break;
default:
console.log('Not found');
}
Run Code Online (Sandbox Code Playgroud)
是相同的:
switch(x) {
case 'The pyramids of Giza':
console.log('The pyramids of Giza');
break;
case 'The Leaning Tower of Pisa':
console.log('The Leaning Tower of Pisa');
break;
default:
console.log('Not found');
}
Run Code Online (Sandbox Code Playgroud)
纯粹出于效率目的,谢谢!
您可以在switch语句中访问要测试的变量;毕竟,如果x等于“吉萨金字塔”,那么它x也必须是您希望在其中使用的值case。
switch(x) {
case 'The pyramids of Giza':
console.log(x); // output: 'The pyramids of Giza'
break;
case 'The Leaning Tower of Pisa':
console.log(x); // output: 'The Leaning Tower of Pisa'
break;
default:
console.log('Not found');
}
Run Code Online (Sandbox Code Playgroud)