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

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

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

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

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


当前回答

如果有其他代码将布尔值转换为字符串,您需要确切地知道该代码如何存储真/假值。要么这样,要么您需要访问反转转换的函数。

有无数种方法可以在字符串中表示布尔值(“true”、“Y”、“1”等)。因此,您不应该依赖一些通用的字符串到布尔值转换器,如布尔值(myValue)。您需要使用一个例程来反转原始布尔值到字符串的转换,无论是什么。

如果您知道它将真布尔值转换为“真”字符串,那么您的示例代码就可以了。除了您应该使用==而不是==,因此没有自动类型转换。

其他回答

对于null、undefined、“”、“false”,“toBoolean”函数返回false。对于任何其他字符串,它都返回true:

const toBoolean = (bool) => {
  if (bool === 'false') bool = false
  return !!bool
}

toBoolean('false') // returns false

使用这个库要轻松。

https://github.com/rohmanhm/force-boolean

你只需要写一行

const ForceBoolean = require('force-boolean')

const YOUR_VAR = 'false'
console.log(ForceBoolean(YOUR_VAR)) // it's return boolean false

它还支持以下内容

 return false if value is number 0
 return false if value is string '0'
 return false if value is string 'false'
 return false if value is boolean false
 return true if value is number 1
 return true if value is string '1'
 return true if value is string 'true'
 return true if value is boolean true

我需要一个将任何变量类型转换为布尔值的代码。下面是我想到的:

常量toBoolean=(x)=>{if(类型x===“对象”){for(x中的var i)返回truereturn false}返回(x!==null)&&(x!=undefined)&&!['false',“”,“0”,“no”,“off”].includes(x.toString().toLowerCase())}

让我们测试一下!

常量toBoolean=(x)=>{if(类型x===“对象”){for(x中的var i)返回truereturn false}返回(x!==null)&&(x!=undefined)&&!['false',“”,“0”,“no”,“off”].includes(x.toString().toLowerCase())}//让我们测试一下!let falseValues=[false,'false',0,'','off','no',[],{},null,undefined]let trueValues=[true,'true','true',1,-1,'Anything',['填充数组'],{'具有任意键的对象':null}]falseValues.forEach((value,index)=>console.log(`类型为${typeof value}的False值${index}:${value}->${toBoolean(value)}`))trueValues.forEach((value,index)=>console.log(`类型为${typeof value}的True value${index}:${value}->${toBoolean(value)}`))

如果单词“off”和“no”与您的大小写不符,您可以从数组中删除它们。

function convertBoolean(value): boolean {
    if (typeof value == 'string') {
        value = value.toLowerCase();
    }
    switch (value) {
        case true:
        case "true":
        case "evet": // Locale
        case "t":
        case "e": // Locale
        case "1":
        case "on":
        case "yes":
        case 1:
            return true;
        case false:
        case "false":
        case "hayır": // Locale
        case "f":
        case "h": // Locale
        case "0":
        case "off":
        case "no":
        case 0:
            return false;
        default:
            return null;
    }
}

这是从公认的答案中得出的,但实际上它有一个非常薄弱的地方,我很震惊它是如何获得支持票的,它的问题是你必须考虑字符串的大小写,因为这是区分大小写的

var isTrueSet = (myValue.toLowerCase() === 'true');