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

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

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

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

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


当前回答

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

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

其他回答

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

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

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

我认为@Steven的答案是最好的,并且比传入的值只是一个字符串时处理了更多的情况。我想稍微扩展一下,并提供以下内容:

function isTrue(value){
    if (typeof(value) === 'string'){
        value = value.trim().toLowerCase();
    }
    switch(value){
        case true:
        case "true":
        case 1:
        case "1":
        case "on":
        case "yes":
            return true;
        default: 
            return false;
    }
}

如果你已经知道所有你需要解释的真实案例,那么就不必涵盖所有的虚假案例。您可以向该方法传递任何可以传递真值的值(或添加其他值,这很简单),其他所有值都将被视为假

if (String(a) == "true"){
  //true block
} else {
  //false block
}

只需执行以下操作:

var myBool = eval (yourString);

示例:

alert (eval ("true") == true); // TRUE
alert (eval ("true") == false); // FALSE
alert (eval ("1") == true); // TRUE
alert (eval ("1") == false); // FALSE
alert (eval ("false") == true); // FALSE;
alert (eval ("false") == false); // TRUE
alert (eval ("0") == true); // FALSE
alert (eval ("0") == false); // TRUE
alert (eval ("") == undefined); // TRUE
alert (eval () == undefined); // TRUE

该方法自然地处理空字符串和未定义字符串,就像您声明变量而不为其赋值一样。

在一行代码中将字符串转换为布尔值的最快安全方法

有助于加快Javascript中代码执行的一个特性是短路评估:

当逻辑表达式从左到右求值时,使用以下规则对其进行可能的“短路”求值测试:false&(任何东西)短路评估为false。true||(任何东西)被短路评估为真。

因此,如果您想在JSON.parse测试方式中测试字符串值是否为true或false,并保持强大的性能,则可以使用||运算符在测试值为布尔类型的情况下将慢速代码排除在执行之外。

test === true || ['true','yes','1'].indexOf(test.toString().toLowerCase()) > -1

由于Array.prototype.indexOf()方法是第5版ECMA-262标准的一部分,您可能需要一个polyfill来支持旧浏览器。

// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let O be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of O with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in O && O[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}