JavaScript:解析字符串布尔值? [英] JavaScript: Parsing a string Boolean value?

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

问题描述

JavaScript 有 parseInt()parseFloat(),但没有 parseBoolparseBoolean 方法在全球范围,据我所知.

我需要一个方法,它接受带有true"或false"等值的字符串并返回一个 JavaScript Boolean.

这是我的实现:

function parseBool(value) {return (typeof value === "undefined") ?错误的 ://使用 jQuery.trim() 的源进行修剪value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";}

这个功能好吗?请给我您的反馈.

谢谢!

解决方案

我倾向于用三元 if 做一个单行.

var bool_value = value == "true" ?真假

甚至更快的是避免使用逻辑语句,而只使用表达式本身:

var bool_value = value == 'true';

这是可行的,因为 value == 'true' 是根据 value 变量是否是 'true' 的字符串来计算的.如果是,则整个表达式变为 true,如果不是,则变为 false,然后在评估后将该结果分配给 bool_value.>

JavaScript has parseInt() and parseFloat(), but there's no parseBool or parseBoolean method in the global scope, as far as I'm aware.

I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean.

Here's my implementation:

function parseBool(value) {
    return (typeof value === "undefined") ? 
           false : 
           // trim using jQuery.trim()'s source 
           value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}

Is this a good function? Please give me your feedback.

Thanks!

解决方案

I would be inclined to do a one liner with a ternary if.

var bool_value = value == "true" ? true : false

Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:

var bool_value = value == 'true';

This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.

这篇关于JavaScript:解析字符串布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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