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

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

问题描述

我通过将truthy布尔值传递给函数来在脚本中设置模式。在函数中,一个简单的 if 语句检查param是否为 true false 。我有时将它作为一个字符串或一直使用的bool传递,但由于某种原因它不适用于此:

  setMode:function(Setting){
if(Setting){
console.log('Enabling mode');
} else {
console.log('禁用模式');
}
}

例如,当我传递一个字符串'false'并记录设置到控制台,控制台说 false ,但是 if if 语句认为它是真的。



我必须将它添加到函数的开头,工作:

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

解决方案

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


如果参数是空字符串(其长度为零),则此转换结果为false。

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



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

  if(elem.prop(checked))

这里


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');
    }
}

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') { Setting = (Setting == "true"); }

An example of it in use:

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

and another:

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

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 SPEC:

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

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.

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"))

like here.

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

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