JavaScript IF 语句 boolean 严格 [英] JavaScript IF statement boolean strict

查看:30
本文介绍了JavaScript IF 语句 boolean 严格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过将真实"布尔值传递给函数来在脚本中设置模式.在函数中,一个简单的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"))

喜欢这里.

这篇关于JavaScript IF 语句 boolean 严格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆