开发者

Converting a string into a boolean [duplicate]

开发者 https://www.devze.com 2022-12-19 02:34 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: How can I convert a string to boolean in JavaScript?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How can I convert a string to boolean in JavaScript?

I have a hidden field that contains a boolean value, I am checking if it's true or false in a JavaScript function, like this:

if (Trim(document.forms['mainform'].hiddenfield.value) == 'true')
{
}

which I think is a lame way to do this. How to convert that string value into a bo开发者_如何学编程olean?


This may seem a bit silly, but you could add a method to String.

String.prototype.isTrue = function() {
   return this.toLowercase() == "true"
}

gives you

>>> "true".isTrue()
true
>>> var x = "false"
>>> x.isTrue()
false

just use .isTrue() on any string literal or variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消