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

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

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

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

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


当前回答

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

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

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

其他回答

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

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

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

另一种解决方案。jsFiddle公司

var toBoolean = function(value) {
    var strValue = String(value).toLowerCase();
    strValue = ((!isNaN(strValue) && strValue !== '0') &&
        strValue !== '' &&
        strValue !== 'null' &&
        strValue !== 'undefined') ? '1' : strValue;
    return strValue === 'true' || strValue === '1' ? true : false
};

测试用例在节点中运行

> toBoolean(true)
true
> toBoolean(false)
false
> toBoolean(undefined)
false
> toBoolean(null)
false
> toBoolean('true')
true
> toBoolean('True')
true
> toBoolean('False')
false
> toBoolean('false')
false
> toBoolean('0')
false
> toBoolean('1')
true
> toBoolean('100')
true
> 

许多现有答案使用与此语义相似的方法,但我认为值得一提的是,以下“一行”通常就足够了。例如,除了OP的情况(表单中的字符串)外,人们还经常希望从NodeJS中的process.env中读取环境变量(据我所知,其值始终是字符串),以便启用或禁用某些行为,并且这些变量的格式通常为SOME_env_VAR=1。

const toBooleanSimple = (input) => 
  ['t', 'y', '1'].some(truePrefix => truePrefix === input[0].toLowerCase());

一个稍微更健壮、更具表现力的实现可能如下所示:

/**
 * Converts strings to booleans in a manner that is less surprising
 * to the non-JS world (e.g. returns true for "1", "yes", "True", etc.
 * and false for "0", "No", "false", etc.)
 * @param input
 * @returns {boolean}
 */
function toBoolean(input) {
  if (typeof input !== 'string') {
    return Boolean(input);
  }
  const s = input.toLowerCase();
  return ['t', 'y', '1'].some(prefix => s.startsWith(prefix));
}

对此的(玩笑)单元测试可能如下所示:

describe(`toBoolean`, function() {
  const groups = [{
    inputs: ['y', 'Yes', 'true', '1', true, 1],
    expectedOutput: true
  }, {
    inputs: ['n', 'No', 'false', '0', false, 0],
    expectedOutput: false
  }]
  for (let group of groups) {
    for (let input of group.inputs) {
      it(`should return ${group.expectedOutput} for ${JSON.stringify(input)}`, function() {
        expect(toBoolean(input)).toEqual(group.expectedOutput);
      });
    }      
  }
});

试试这个解决方案(它就像一个魅力!):

function convertStrToBool(str)
    {
        switch(String(str).toLowerCase())
            {
                case 'undefined': case 'null': case 'nan': case 'false': case 'no': case 'f': case 'n': case '0': case 'off': case '':
                    return false;
                    break;
                default:
                    return true;
            };
    };

我一直使用的最简单的方法:

let value = 'true';
let output = value === 'true';