JavaScript IF 语句 boolean strict

2022-01-19 00:00:00 if-statement boolean jquery javascript html

我通过将真实"布尔值传递给函数来在脚本中设置模式.在函数中,一个简单的 if 语句检查参数是 true 还是 false.我有时将它作为一直有效的字符串或布尔值传递,但由于某种原因它不是为此:

I am setting a mode in a script by passing a "truthy" boolean to a function. In the function a simple if statement checks if the param is true or false. I sometimes pass it as a string or a bool which has always worked, but for some reason it isn't for this:

setMode: function(Setting) {    
    if (Setting) {
        console.log('Enabling mode');
    } else {
        console.log('Disabling mode');
    }
}

例如,当我向它传递一个字符串 'false' 并将 Setting 记录到控制台时,控制台说 false,但 >if 语句认为是真的.

For example when I pass it a string 'false' and log Setting to console, the console says false, yet the if statement thinks it's true.

我必须将其添加到函数的开头才能使其工作:

I have to add this to the start of the function for it to work:

if (typeof Setting == 'string') {设置=(设置==真");}

if (typeof Setting == 'string') { Setting = (Setting == "true"); }

使用示例:

var inverted = $('INPUT[name="Mode"]').prop('checked');
app.setMode(inverted);

还有一个:

var mode = localStorage.getItem('Mode');
this.setMode(mode);

这太奇怪了,因为我已经做了很多年了,但现在才刚刚开始.可能是因为我使用的是 localStorage.prop?

It's so bizarre since I've done this type of thing for years yet it's only starting now. Maybe because I'm using localStorage and .prop?

推荐答案

回答关于字符串到布尔转换的问题:

To answer your question about string to boolean conversions:

ECMA 规范:

如果参数是空字符串(其长度为零),则[此转换的]结果为假;否则结果为真.

The result [of this conversion] is false if the argument is the empty String (its length is zero); otherwise the result is true.

所以是的,如果您传递字符串false",它将被转换为 true,这意味着您唯一的选择是手动检查字符串true"或false"并且自己做转换.

So yes, if you pass the string "false" it will be converted to true, which means the only option you have is to manually check for the strings "true" or "false" and do the conversion by yourself.

然而,jQuery 函数 .prop("checked") 应该返回一个布尔值(如果属性未定义,则返回 undefined).所以我会说你应该能够真正做到

However, the jQuery function .prop("checked") is supposed to return a boolean value (or undefined if the property is not defined). So I would say you should be able to actually do

if (elem.prop("checked"))

喜欢这里.

相关文章