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

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

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

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

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


当前回答

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

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

toBoolean('false') // returns false

其他回答

我使用这个简单的方法(使用“myVarToTest”):

var trueValuesRange = ['1', 1, 'true', true];

myVarToTest = (trueValuesRange.indexOf(myVarToTest) >= 0);

为了计算布尔值和类似布尔值的字符串,我使用了以下简单公式:

var trueOrStringTrue = (trueOrStringTrue === true) || (trueOrStringTrue === 'true');

显然,对于true和“true”,它都将返回true。其他一切都返回false。

这是我提交的一行代码:我需要计算一个字符串和输出,如果为“true”,则为true,如果为false,则为false;如果为“-12.35673”,则是一个数字。

val = 'false';

val = /^false$/i.test(val) ? false : ( /^true$/i.test(val) ? true : val*1 ? val*1 : val );

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

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

你的解决方案很好。

在这种情况下,使用==是愚蠢的,因为字段的值始终是字符串。