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

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

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

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == '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;
  };
}

其他回答

在HTML中,属性的值最终变成字符串。为了在不希望出现的情况下减轻这种情况,您可以使用一个函数将它们有条件地解析为它们在JavaScript或任何其他感兴趣的编程语言中表示的值。

以下是从字符串类型恢复布尔类型的说明,但它也可以进一步扩展到其他数据类型,如数字、数组或对象。

除此之外,JSON.parse还有一个作为函数的复活参数。它也可以用来实现同样的目的。

让我们调用一个看起来像布尔值的字符串“true”,一个布尔值字符串,同样我们也可以调用一个像数字“1”的字符串,一个数字字符串。然后我们可以确定字符串是否为布尔字符串:

const isBooleanString = (string) => ['true', 'false'].some(item => item === string);

之后,我们需要通过JSON.parse方法将布尔字符串解析为JSON:

JSON.parse(aBooleanString);

但是,任何不是布尔字符串、数字字符串或任何字符串化对象或数组(任何无效的JSON)的字符串都会导致JSON.parse方法抛出SyntaxError。

因此,您需要知道如何调用它,即它是否为布尔字符串。您可以通过编写一个函数来实现这一点,该函数进行上述定义的布尔字符串检查并调用JSON.parse:

function parse(string){
  return isBooleanString(string) ? JSON.parse(string)
    : string;
}

通过进一步参数化isBooleanString实用程序以接受接受的布尔字符串的可选数组,可以进一步概括isBooleanString实用程序,从而对什么是布尔字符串具有更广泛的视角:

const isBooleanString = (string, spec = ['true', 'false', 'True', 'False']) => spec.some(item => item === string);
function isTrue(val) {
    try {
        return !!JSON.parse(val);
    } catch {
        return false;
    }
}

我使用以下方法:

function parseBool(b) {
    return !(/^(false|0)$/i).test(b) && !!b;
}

此函数执行通常的布尔强制,字符串“false”(不区分大小写)和“0”除外。

你需要(在你的思维中)将你的选择的价值和价值的表示分开。

在JavaScript逻辑中选择一个需要从字符串标记转换为原生类型的点,并在那里进行比较,最好是对每个需要转换的值只进行一次比较。记住,如果字符串sentinel不是脚本所知道的(即默认为true还是false?)

换句话说,是的,您需要依赖于字符串的值。:-)

我使用自己的方法,其中包括检查对象是否首先存在,以及更直观地转换为布尔值:

function str2bool(strvalue){
  return (strvalue && typeof strvalue == 'string') ? (strvalue.toLowerCase() == 'true' || strvalue == '1') : (strvalue == true);
}

结果如下:

var test; // false
var test2 = null; // false
var test3 = 'undefined'; // false
var test4 = 'true'; // true
var test5 = 'false'; // false
var test6 = true; // true
var test7 = false; // false
var test8 = 1; // true
var test9 = 0; // false
var test10 = '1'; // true
var test11 = '0'; // false

小提琴:http://jsfiddle.net/av5xcj6s/