Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

jquery - JavaScript IF statement boolean strict

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you try to log 'false' it is obvious that console logs false(it is a string) and that the if statement sees true, because a not-empty string is a true boolean value.

If you want to check if the string is "true" or "false" you have to do it with normal operators. So you could add this line at the beginning of your function:

Setting = (typeof Setting === 'string') ? Setting === "true" : Setting;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...