Cast a bool in JavaScript
Possible Duplicate:
How can I convert a string to boolean in JavaScript?
Hi,
How can I cast a String in Bool ?
Example: "False" to bool false
I need this for my JavaScript.
Thank you for help !
function castStrToBool(str){
if (str.toLowerCase()=='false'){
return false;
} else if (str.toLowerCase()=='true'){
return true;
} else {
return undefined;
}
}
......但我认为乔恩的回答更好!
You can do this:
var bool = !!someString;
If you do that, you'll discover that the string constant "False"
is in fact boolean true
. Why? Because those are the rules in Javascript. Anything that's not undefined
, null
, the empty string ( ""
), or numeric zero is considered true
.
If you want to impose your own rules for strings (a dubious idea, but it's your software), you could write a function with a lookup table to return values:
function isStringTrue(s) {
var falses = { "false": true, "False": true };
return !falses[s];
}
maybe.
edit — fixed the typo - thanks @Patrick
你可以使用类似这样的东西来为字符串提供你自己的定制“真实”测试,同时让其他类型的比较不受影响:
function isTrue(input) {
if (typeof input == 'string') {
return input.toLowerCase() == 'true';
}
return !!input;
}
链接地址: http://www.djcxy.com/p/75070.html
上一篇: 最干净的方式来转换为布尔值
下一篇: 在JavaScript中投射一个布尔