简体   繁体   English

如果声明出于某种原因表现得很奇怪

[英]If statement is acting weird for some reason

So I have an if statement that is checking the values of a drop down. 所以我有一个if语句检查下拉列表的值。 The user has to select at least one of them to continue. 用户必须至少选择其中一个才能继续。 The values are just numbers. 值只是数字。 My if statement checks to see that, basically, the values are equal to zero: 我的if语句检查看,基本上,这些值等于零:

if (numChildren === 0 && numAdults === 0){
    Than do this
}

But for some reason it keep returning false. 但由于某种原因,它不断返回虚假。 I have console logged the numChildren and adults to see what there values are and they are zero I have no idea why it isn't working I have put a "!" 我有控制台登录numChildren和成年人,看看有什么价值,他们是零我不知道为什么它不工作我已经把“!” before it to cause it to be true but then it remains false. 在它之前使它成为真实然后它仍然是假的。 It is a very weird error. 这是一个非常奇怪的错误。

$("#Discounts").on("click", function () {
        let numChildren = $("#children").val();
        let numAdults = $("#adults").val();
        console.log("Adults: " + numAdults + "\nChildren: " + numChildren);
        console.log(numChildren === 0 && numAdults === 0);
        if (numChildren === 0 && numAdults === 0) {
            alert("You must select");
            $("#children").val(1);
        }
    });

It's not weird. 这并不奇怪。

You are using the triple equal comparison and, probably, the numChildren contains a number in string form (like "0") which you are comparing to zero as an actual number. 您正在使用三重相等比较,并且可能, numChildren包含一个字符串形式的数字(如“0”),您将其作为实际数字与zero进行比较。

It should work with: 它应该与:

numChildren == 0 && numAdults == 0

or 要么

Number(numChildren) === 0 && Number(numAdults) === 0

This is the official reference: https://tc39.github.io/ecma262/#sec-strict-equality-comparison 这是官方参考: https//tc39.github.io/ecma262/#sec-strict-equality-comparison

When you use 3 equals in a if statement the numChildren must be the same type and value as 0 (integer), not just equal to 0. 在if语句中使用3 equals时, numChildren必须是与0(整数)相同的类型和值,而不仅仅是0。

Try changing to 2 equals: 尝试更改为2等于:

if (numChildren == 0 && numAdults == 0) {
            alert("You must select");
            $("#children").val(1);
        }

Reference 参考

You can try this: 你可以试试这个:

if (Number(numChildren) === 0 && Number(numAdults) === 0) {
        alert("You must select");
        $("#children").val(1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM