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

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

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

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

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


当前回答

我希望这是一个最全面的用例

function parseBoolean(token) {
  if (typeof token === 'string') {
    switch (token.toLowerCase()) {
      case 'on':
      case 'yes':
      case 'ok':
      case 'ja':
      case 'да':
      // case '':
      // case '':
        token = true;
        break;
      default:
        token = false;
    }
  }
  let ret = false;
  try {
    ret = Boolean(JSON.parse(token));
  } catch (e) {
    // do nothing or make a notification
  }
  return ret;
}

其他回答

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

另一种解决方案。jsFiddle公司

var toBoolean = function(value) {
    var strValue = String(value).toLowerCase();
    strValue = ((!isNaN(strValue) && strValue !== '0') &&
        strValue !== '' &&
        strValue !== 'null' &&
        strValue !== 'undefined') ? '1' : strValue;
    return strValue === 'true' || strValue === '1' ? true : false
};

测试用例在节点中运行

> toBoolean(true)
true
> toBoolean(false)
false
> toBoolean(undefined)
false
> toBoolean(null)
false
> toBoolean('true')
true
> toBoolean('True')
true
> toBoolean('False')
false
> toBoolean('false')
false
> toBoolean('0')
false
> toBoolean('1')
true
> toBoolean('100')
true
> 

最简单的方法(假设字符串为“true”或“false”)是:

var z = 'true';
var y = 'false';
var b = (z === 'true'); // will evaluate to true
var c = (y === 'true'); // will evaluate to false

对于这些类型的转换,始终使用==运算符而不是==运算符!

以下内容就足够了

String.prototype.boolean = function() {
    return "true" == this; 
};

"true".boolean() // returns true "false".boolean() // returns false

布尔对象没有“parse”方法。布尔值('false')返回true,因此这不起作用。!!'false'也返回true,因此这也不起作用。

如果您希望字符串“true”返回布尔值true,而字符串“false”返回布尔型false,那么最简单的解决方案是使用eval()。eval('true')返回true,eval('false')返回false。

不过,在使用eval()时,请记住性能和安全性的影响。