最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jQuery JavaScript is there a function like parseInt for Boolean - Stack Overflow

programmeradmin0浏览0评论

I know, I know, sounds silly, but I am having this one variable passed around and around and I think somewhere in the midst of it all its losing itself as a Boolean Value, that being the case I need to take said string when it es to one portion of my script and make sure its read as a Boolean. So with that, I am wondering if theres something like the parseInt function but for booleans cause I know when my int's manage to get run through the mill and turn into a string cause of, I sometimes need to invoke a means of making it recognize as integer again.

I know, I know, sounds silly, but I am having this one variable passed around and around and I think somewhere in the midst of it all its losing itself as a Boolean Value, that being the case I need to take said string when it es to one portion of my script and make sure its read as a Boolean. So with that, I am wondering if theres something like the parseInt function but for booleans cause I know when my int's manage to get run through the mill and turn into a string cause of, I sometimes need to invoke a means of making it recognize as integer again.

Share Improve this question asked Jun 15, 2012 at 1:33 chrischris 37k53 gold badges147 silver badges256 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 3
String.prototype.parseBoolean = function ()
{
  return ("true" == this.toLowerCase()) ? true : false
}

no there is no function, there is this shortcut:

var bool = !!something;

or, you can make a new boolean like this:

var bool = Boolean(something)

it works by coercing the value to a boolean. It will use the truthy/falsy value for the variable.

while i am on this topic, there is also:

var floor = ~~3.1415; //floor = 3
function stringToBoolean(string){
    if (typeof string === "undefined") {
        console.log("stringToBoolean Undefined Error");
        return false;
    }
    if (typeof string === "boolean") return string;
    switch(string.toLowerCase()) {
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return false;
    }
}
发布评论

评论列表(0)

  1. 暂无评论