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

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

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

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

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


当前回答

就像@Shadow2531所说的,你不能直接转换它。如果您的代码将被其他人重用/使用,我还建议您考虑“true”和“false”之外的字符串输入,即“truthy”和“falsy”。这是我使用的:

function parseBoolean(string) {
  switch (String(string).toLowerCase()) {
    case "true":
    case "1":
    case "yes":
    case "y":
      return true;
    case "false":
    case "0":
    case "no":
    case "n":
      return false;
    default:
      //you could throw an error, but 'undefined' seems a more logical reply
      return undefined;
  }
}

其他回答

    MyLib.Convert.bool = function(param) {
         var res = String(param).toLowerCase();
         return !(!Boolean(res) || res === "false" || res === "0");
     }; 

从字符串或数字中获取布尔值有一个很好的解决方案:

var boolValue = Boolean(Number('0'));

var boolValue = Boolean(Number('1'));

第一个将返回false,第二个将返回true。

我认为它可以用一个带有使用箭头功能的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));//唯一不起作用的情况

可以使用Function从字符串“true”或“false”返回布尔值

const TRUE_OR_FALSE=str=>新函数(“return${str}”)();const[TRUE,FALSE]=[“TRUE”,“FALSE”];常量[T,F]=[TRUE_OR_FALSE(真),TRUE_OR_FALSE(假)];console.log(T,类型T);//`true``“布尔值”`console.log(F,F类型);//`false``“布尔值”`

基于上面Steven的回答,我编写了这个函数作为字符串输入的通用解析器:

parse:
  function (value) {
    switch (value && value.toLowerCase()) {
      case null: return null;
      case "true": return true;
      case "false": return false;
      default: try { return parseFloat(value); } catch (e) { return value; }
    }
  }