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

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

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

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

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


当前回答

我编写了一个助手函数来处理您的案例(以及其他一些)。根据您的具体需要随意更改

/**
 * @example
 * <code>
 * var pageRequestParams = {'enableFeatureX': 'true'};
 * toBool(pageRequestParams.enableFeatureX);  // returns true
 *
 * toBool(pageRequestParams.enableFeatureY, true, options.enableFeatureY)
 * </code>
 * @param {*}value
 * @param {Boolean}[mapEmptyStringToTrue=false]
 * @param {Boolean}[defaultVal=false] this is returned if value is undefined.
 *
 * @returns {Boolean}
 * @example
 * <code>
 * toBool({'enableFeatureX': ''        }.enableFeatureX);          // false
 * toBool({'enableFeatureX': ''        }.enableFeatureX, true);    // true
 * toBool({                            }.enableFeatureX, true);    // false
 * toBool({'enableFeatureX': 0         }.enableFeatureX);          // false
 * toBool({'enableFeatureX': '0'       }.enableFeatureX);          // false
 * toBool({'enableFeatureX': '0 '      }.enableFeatureX);          // false
 * toBool({'enableFeatureX': 'false'   }.enableFeatureX);          // false
 * toBool({'enableFeatureX': 'falsE '  }.enableFeatureX);          // false
 * toBool({'enableFeatureX': 'no'      }.enableFeatureX);          // false
 *
 * toBool({'enableFeatureX': 1         }.enableFeatureX);          // true
 * toBool({'enableFeatureX': '-2'      }.enableFeatureX);          // true
 * toBool({'enableFeatureX': 'true'    }.enableFeatureX);          // true
 * toBool({'enableFeatureX': 'false_'  }.enableFeatureX);          // true
 * toBool({'enableFeatureX': 'john doe'}.enableFeatureX);          // true
 * </code>
 *
 */
var toBool = function (value, mapEmptyStringToTrue, defaultVal) {
    if (value === undefined) {return Boolean(defaultVal); }
    mapEmptyStringToTrue = mapEmptyStringToTrue !== undefined ? mapEmptyStringToTrue : false; // default to false
    var strFalseValues = ['0', 'false', 'no'].concat(!mapEmptyStringToTrue ? [''] : []);
    if (typeof value === 'string') {
        return (strFalseValues.indexOf(value.toLowerCase().trim()) === -1);
    }
    // value is likely null, boolean, or number
    return Boolean(value);
};

其他回答

在typescript中,如果值是以字符串、数字或布尔形式传递的,则需要处理的一个小函数,例如“true”、“false”、true、false、1或0。

const getAsBoolean = (value: string | boolean | number) => {
  if (typeof value === 'string') {
    return value === 'true';
  } else if (typeof value === 'boolean' || typeof value === 'number') {
    return Boolean(value);
  } else {
    return undefined;
  }
};
var trueVals = ["y", "t", "yes", "true", "gimme"];
var isTrueSet = (trueVals.indexOf(myValue) > -1) ? true : false;

甚至只是

var trueVals = ["y", "t", "yes", "true", "gimme"];
var isTrueSet = (trueVals.indexOf(myValue) > -1);

类似于一些switch语句,但更紧凑。只有当字符串是trueVals字符串之一时,返回的值才会为true。其他一切都是假的。当然,您可能希望对输入字符串进行规范化,使其变为小写,并修剪任何空格。

使用这个库要轻松。

https://github.com/rohmanhm/force-boolean

你只需要写一行

const ForceBoolean = require('force-boolean')

const YOUR_VAR = 'false'
console.log(ForceBoolean(YOUR_VAR)) // it's return boolean false

它还支持以下内容

 return false if value is number 0
 return false if value is string '0'
 return false if value is string 'false'
 return false if value is boolean false
 return true if value is number 1
 return true if value is string '1'
 return true if value is string 'true'
 return true if value is boolean true
function convertBoolean(value): boolean {
    if (typeof value == 'string') {
        value = value.toLowerCase();
    }
    switch (value) {
        case true:
        case "true":
        case "evet": // Locale
        case "t":
        case "e": // Locale
        case "1":
        case "on":
        case "yes":
        case 1:
            return true;
        case false:
        case "false":
        case "hayır": // Locale
        case "f":
        case "h": // Locale
        case "0":
        case "off":
        case "no":
        case 0:
            return false;
        default:
            return null;
    }
}

在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);