我可以在JavaScript中将表示布尔值的字符串(例如“true”、“false”)转换为内部类型吗?

我有一个隐藏的HTML表单,它根据用户在列表中的选择进行更新。此表单包含一些表示布尔值的字段,并用内部布尔值动态填充。但是,一旦将该值放入隐藏的输入字段,它就会变成字符串。

一旦字段转换为字符串,我唯一能找到的确定它的布尔值的方法就是依赖于它的字符串表示的文字值。

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

有没有更好的方法来实现这一点?


当前回答

可以使用正则表达式:

/*
 * Converts a string to a bool.
 *
 * This conversion will:
 *
 *  - match 'true', 'on', or '1' as true.
 *  - ignore all white-space padding
 *  - ignore capitalization (case).
 *
 * '  tRue  ','ON', and '1   ' will all evaluate as true.
 *
 */
function strToBool(s)
{
    // will match one and only one of the string 'true','1', or 'on' rerardless
    // of capitalization and regardless off surrounding white-space.
    //
    regex=/^\s*(true|1|on)\s*$/i

    return regex.test(s);
}

如果您喜欢扩展String类,可以执行以下操作:

String.prototype.bool = function() {
    return strToBool(this);
};

alert("true".bool());

对于那些希望扩展String对象以获得此结果但担心可枚举性并担心与扩展String对象的其他代码冲突的人(请参见注释):

Object.defineProperty(String.prototype, "com_example_bool", {
    get : function() {
        return (/^(true|1)$/i).test(this);
    }
});
alert("true".com_example_bool);

(当然在旧版浏览器中不起作用,Firefox显示错误,而Opera、Chrome、Safari和IE显示正确。错误720760)

其他回答

警告:切勿将此方法用于不受信任的输入,例如URL参数。

可以使用eval()函数。直接将字符串传递给eval()函数。

console.log(eval('true'),类型为eval('true'))console.log(eval('false'),eval类型('false'))

在HTML中,属性的值最终变成字符串。为了在不希望出现的情况下减轻这种情况,您可以使用一个函数将它们有条件地解析为它们在JavaScript或任何其他感兴趣的编程语言中表示的值。

以下是从字符串类型恢复布尔类型的说明,但它也可以进一步扩展到其他数据类型,如数字、数组或对象。

除此之外,JSON.parse还有一个作为函数的复活参数。它也可以用来实现同样的目的。

让我们调用一个看起来像布尔值的字符串“true”,一个布尔值字符串,同样我们也可以调用一个像数字“1”的字符串,一个数字字符串。然后我们可以确定字符串是否为布尔字符串:

const isBooleanString = (string) => ['true', 'false'].some(item => item === string);

之后,我们需要通过JSON.parse方法将布尔字符串解析为JSON:

JSON.parse(aBooleanString);

但是,任何不是布尔字符串、数字字符串或任何字符串化对象或数组(任何无效的JSON)的字符串都会导致JSON.parse方法抛出SyntaxError。

因此,您需要知道如何调用它,即它是否为布尔字符串。您可以通过编写一个函数来实现这一点,该函数进行上述定义的布尔字符串检查并调用JSON.parse:

function parse(string){
  return isBooleanString(string) ? JSON.parse(string)
    : string;
}

通过进一步参数化isBooleanString实用程序以接受接受的布尔字符串的可选数组,可以进一步概括isBooleanString实用程序,从而对什么是布尔字符串具有更广泛的视角:

const isBooleanString = (string, spec = ['true', 'false', 'True', 'False']) => spec.some(item => item === string);

这是我最近遇到的最简单的布尔转换方法。考虑添加它。

JSON.parse('true');

let trueRespons=JSON.parse('true');let falseResponse=JSON.parse('false');console.log(trueResponse);console.log(错误响应);

当我从URL/Form或其他来源获取值时,我会使用这个。

这是非常通用的一行代码。

也许不是性能最好的,如果您需要运行数百万次,请告诉我,我们可以检查如何优化它,否则非常好,可以自定义。

boolResult = !(['false', '0', '', 'undefined'].indexOf(String(myVar).toLowerCase().trim()) + 1);

结果:

myVar = true;  // true
myVar = 'true';  // true
myVar = 'TRUE';  // true
myVar = '1';  // true
myVar = 'any other value not related to false';  // true

myVar = false; // false
myVar = 'false';  // false
myVar = 'FALSE';  // false
myVar = '0';  // false

我认为它可以用一个带有使用箭头功能的1行代码完成

const convertStringToBoolean = (value) => value ? String(value).toLowerCase() === 'true' : false;

你们可以使用以下代码段运行和测试各种情况

const convertStringToBoolean=(value)=>value?字符串(值).toLowerCase()==“true”:false;console.log(convertStringToBoolean(“a”));console.log(convertStringToBoolean(null));console.log(convertStringToBoolean(未定义));console.log(convertStringToBoolean(“undefined”));console.log(convertStringToBoolean(true));console.log(convertStringToBoolean(false));console.log(convertStringToBoolean(0));console.log(convertStringToBoolean(1));//唯一不起作用的情况