JavaScript切换语句-可以使用用例值

JavaScript Switch Statements - possible to use case value?

本文关键字:可以使 语句 JavaScript      更新时间:2023-09-26

我想知道在执行代码块时,是否可以在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等于"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');
}
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');
}

应该做的技巧

如果你在HTML中返回值,你可以这样写

switch(x) {
    case 'The pyramids of Giza':
        return `<button class="badge text-white">${x}</button>`
        break;
    case 'The Leaning Tower of Pisa':
        return `<button class="badge text-blue">${x}</button>`
        break;
    default:
        console.log('Not Found');
}