JavaScript Switch 语句 - 可能用例值?
JavaScript Switch Statements - possible to use case value?
我想知道在执行代码块时是否可以在 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');
}
等同于:
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');
}
这纯粹是为了提高效率,谢谢!
switch(x) {
case 'The pyramids of Giza':
console.log(x);
break;
case 'The Leaning Tower of Pisa':
console.log(x);
break;
default:
console.log('Not Found');
}
应该可以解决问题
您可以访问您在 switch
语句中测试的变量;毕竟,如果 x
等于 "The pyramids of Giza",那么 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');
}
当你访问一个case:
时,case:
中指定的值的值总是放在switch
语句中的变量。这是因为只有当变量首先等于 case:
中指定的值时才会访问 case:
,所以你知道如果你已经访问过这种情况,那么变量的值必须与 case:
中指定的值相同。因此,这就是您要查找的代码:
switch(x) {
case 'The pyramids of Giza':
console.log(x);
break;
case 'The Leaning Tower of Pisa':
console.log(x);
break;
default:
console.log('Not found');
}
我想知道在执行代码块时是否可以在 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');
}
等同于:
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');
}
这纯粹是为了提高效率,谢谢!
switch(x) {
case 'The pyramids of Giza':
console.log(x);
break;
case 'The Leaning Tower of Pisa':
console.log(x);
break;
default:
console.log('Not Found');
}
应该可以解决问题
您可以访问您在 switch
语句中测试的变量;毕竟,如果 x
等于 "The pyramids of Giza",那么 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');
}
当你访问一个case:
时,case:
中指定的值的值总是放在switch
语句中的变量。这是因为只有当变量首先等于 case:
中指定的值时才会访问 case:
,所以你知道如果你已经访问过这种情况,那么变量的值必须与 case:
中指定的值相同。因此,这就是您要查找的代码:
switch(x) {
case 'The pyramids of Giza':
console.log(x);
break;
case 'The Leaning Tower of Pisa':
console.log(x);
break;
default:
console.log('Not found');
}