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

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

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

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

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


当前回答

if (String(a) == "true"){
  //true block
} else {
  //false block
}

其他回答

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

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

toBoolean('false') // returns false

许多现有答案使用与此语义相似的方法,但我认为值得一提的是,以下“一行”通常就足够了。例如,除了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);
      });
    }      
  }
});

如果您确定测试主题始终是字符串,那么明确检查它是否为true是最佳选择。

您可能需要考虑添加额外的代码,以防主题实际上是布尔值。

var isTrueSet =
    myValue === true ||
    myValue != null &&
    myValue.toString().toLowerCase() === 'true';

如果代码得到改进/重构以使用实际的布尔值而不是字符串,这将在将来为您节省一些工作。

就像@Shadow2531所说的,你不能直接转换它。如果您的代码将被其他人重用/使用,我还建议您考虑“true”和“false”之外的字符串输入,即“truthy”和“falsy”。这是我使用的:

function parseBoolean(string) {
  switch (String(string).toLowerCase()) {
    case "true":
    case "1":
    case "yes":
    case "y":
      return true;
    case "false":
    case "0":
    case "no":
    case "n":
      return false;
    default:
      //you could throw an error, but 'undefined' seems a more logical reply
      return undefined;
  }
}

布尔(value)的简写是!!价值,这是因为!将值转换为与当前值相反的值,然后!将其再次反转为原始形式。