我正在使用 indexof('custom'),它在 1 个条件下工作,但在另一个条件下失败



嗨,我在购物车中输入了itemname和carttotal。

if (carttotal >'500' && itemname.indexOf("Custom") == 0)   
    {
    //code to display popup
    }

有两种情况,一种是正常的,另一种是失败的:

工作状态:如果我最后添加itemname "custom",那么它工作:

。:

购物车中的第一件商品为"abc",最后一件商品名称为"custom",carttotal>500。然后弹出显示fine

不工作的情况:如果我添加itemname "custom",然后我添加了一些项目,如"xyz"。cartotal大于500。

您当前的代码检查Custom是否为列表(0的索引)中的第一个项。您真正想要做的是,检查Custom是否存在在列表中的任何位置,看看indexOf('Custom')是否返回> -1的值,因为-1indexOf()的失败值,而不是0或另一个错误值。例如:

var carttotal = /* Your cart total */
var products = [ /* Lots of products */ ];
for(var i = 0; i < products.length; i++) {
    itemname = products[i];
    if(carttotal > 500 && products.indexOf('Custom') > -1) {    // `products`, not `itemname`
        // Popup
    }
}

在这里,我也检查了products,假设这是你的产品数组。如果itemname是,那么使用它

最新更新