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

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

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

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

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


当前回答

警告

这个高度支持的传统答案在技术上是正确的,但仅适用于非常特定的场景,当字符串值完全为“true”或“false”时。

传递到下面这些函数的无效json字符串将引发异常。


原答覆:

怎么样

JSON.parse("True".toLowerCase());

或使用jQuery

$.parseJSON("TRUE".toLowerCase());

其他回答

我有点晚了,但我有一个小片段要做,它本质上维护了所有JScripts truthey/falsey/dirty ness,但包含“false”作为false的可接受值。

与上述方法相比,我更喜欢这种方法,因为它不依赖第三方来解析代码(即:eval/JSON.parse),这在我看来是过度的,它足够短,不需要实用函数,并维护其他truthey/falsy约定。

var value = "false";
var result = (value == "false") != Boolean(value);

// value = "true"  => result = true
// value = "false" => result = false
// value = true    => result = true
// value = false   => result = false
// value = null    => result = false
// value = []      => result = true
// etc..

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

有助于加快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;
  };
}

Do:

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

使用标识运算符(==),当比较的变量具有不同的类型时,它不会进行任何隐式类型转换。

如果字符串为“true”,则将isTrueSet设置为布尔值true;如果字符串为字符串“false”或根本未设置,则将为布尔值false。


不要:

您可能应该谨慎使用这两种方法来满足您的特定需求:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

任何不是空字符串的字符串都将通过使用它们计算为true。尽管它们是我能想到的关于布尔转换的最干净的方法,但我认为它们并不是你想要的。

将字符串(“true”、“false”)和布尔值转换为布尔值

('' + flag) === "true"

标志可以在哪里

 var flag = true
 var flag = "true"
 var flag = false
 var flag = "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; }
    }
  }