为什么我的 jquery switch 语句不起作用

Why isn't my jquery switch statement working?

本文关键字:语句 不起作用 switch jquery 我的 为什么      更新时间:2023-09-26

我正在尝试使用一些简单的运算符进行jquery(javascript)switch语句,但它没有按预期工作

console.log('test '+getShippingCost(8));
function getShippingCost(shop_qty) {
                shipping_costs = 0;
                dest = $("input[name='dest']").val();
                console.log(dest);
                if (dest === 'DOMESTIC') {
                    switch (shop_qty) {
                        case (shop_qty > 4):
                             shipping_costs = 3.5;
                            break;
                        case (shop_qty <= 4):
                             shipping_costs = 2;
                                break;
                        }
                        console.log('domestic shipping '+shipping_costs);
                }
                if (dest === 'INT') {
                            switch (shop_qty) {
                                case (shop_qty > 4):
                                    shipping_costs = 4.5;
                                    break;
                                case (shop_qty <= 4):
                                    shipping_costs = 3;
                                    break;
                            }
                        }
                        return shipping_costs;
                        }//end function

参见 JSFIDDLE

要在switch中使用条件,您需要在案例中查找true值:

switch (true) {
  case (shop_qty > 4):
    shipping_costs = 3.5;
    break;
  case (shop_qty <= 4):
    shipping_costs = 2;
    break;
}

由于第二种情况与第一种情况相反,因此您可以使用default

switch (true) {
  case (shop_qty > 4):
    shipping_costs = 3.5;
    break;
  default:
    shipping_costs = 2;
    break;
}

当您有多个条件时,这种结构更适合。在这种情况下,您应该考虑 if 语句是否更适合:

if (shop_qty > 4) {
    shipping_costs = 3.5;
} else {
    shipping_costs = 2;
}

由于这两种情况都为同一变量赋值,因此您也可以使用条件运算符编写它:

shipping_costs = shop_qty > 4 ? 3.5 : 2;

switch语句中的案例计算值,而不是布尔表达式:请参阅此处。

您可以将尝试使用 switch 语句所建议的逻辑放在三元表达式中,例如:

shipping_costs = (shop_qty > 4) ? 3.5 : 2;

Switch 无法通过计算布尔表达式来工作。Switch 计算初始表达式,然后尝试使用严格相等性将大小写与该表达式匹配。所以你不能做

case(x<4.5):

你必须做这样的事情

case 4:

改用 if、else if、else 语句。