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

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

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

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

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


当前回答

此函数可以处理字符串以及布尔值真/假。

function stringToBoolean(val){
    var a = {
        'true':true,
        'false':false
    };
    return a[val];
}

演示如下:

函数stringToBoolean(val){变量a={'true':真,“false”:false};返回[val];}console.log(stringToBoolean(“true”));console.log(typeof(stringToBoolean(“true”));console.log(stringToBoolean(“false”));console.log(typeof(stringToBoolean(“false”));console.log(stringToBoolean(true));console.log(typeof(stringToBoolean(true)));console.log(stringToBoolean(false));console.log(typeof(stringToBoolean(false)));console.log(“==========================================”);//如果值未定义呢?console.log(“未定义结果:”+stringToBoolean(未定义));console.log(“未定义结果的类型:”+typeof(stringToBoolean(未定义)));console.log(“==========================================”);//如果值是不相关的字符串呢?console.log(“不相关的字符串结果:”+stringToBoolean(“hello world”));console.log(“不相关字符串结果的类型:”+typeof(stringToBoolean(未定义)));

其他回答

许多现有答案使用与此语义相似的方法,但我认为值得一提的是,以下“一行”通常就足够了。例如,除了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 parseBoolean(token) {
  if (typeof token === 'string') {
    switch (token.toLowerCase()) {
      case 'on':
      case 'yes':
      case 'ok':
      case 'ja':
      case 'да':
      // case '':
      // case '':
        token = true;
        break;
      default:
        token = false;
    }
  }
  let ret = false;
  try {
    ret = Boolean(JSON.parse(token));
  } catch (e) {
    // do nothing or make a notification
  }
  return ret;
}

可以使用Function从字符串“true”或“false”返回布尔值

const TRUE_OR_FALSE=str=>新函数(“return${str}”)();const[TRUE,FALSE]=[“TRUE”,“FALSE”];常量[T,F]=[TRUE_OR_FALSE(真),TRUE_OR_FALSE(假)];console.log(T,类型T);//`true``“布尔值”`console.log(F,F类型);//`false``“布尔值”`

var isTrueSet=eval(myValue);

如果使用的是环境变量,请使用以下命令。在Heroku上工作。环境变量是必须转换为布尔值的字符串值。

// Create the database connection
    this.connection = new Sequelize({
      username: process.env.PG_USERNAME,
      password: process.env.PG_PASSWORD,
      database: process.env.PG_DATABASE,
      host: process.env.PG_HOST,
      port: process.env.PG_PORT,
      dialect: process.env.PG_DIALECT,
      dialectOptions: {
        ssl: {
          require: process.env.PG_DIALECT_OPTION_SSL_REQUIRED === 'true', // <<< convert from string to bool
          rejectUnauthorized:
            process.env.PG_DIALECT_OPTION_SSL_REJECT_UNAUTHORIZED === 'true', // <<< convert from string to bool
        },
      },
      logging: true,
    });

env文件

# PostgreSQL Config
PG_USERNAME=ttubkcug
PG_PASSWORD=ea59cee2883e73c602e6c05b674cf16950d6a9f05ab
PG_DATABASE=d67potesdliv25
PG_HOST=ec2-23-333-45-192.compute-1.amazonaws.com
PG_PORT=5432
PG_DIALECT=postgres
PG_DIALECT_OPTION_SSL_REQUIRED=true
PG_DIALECT_OPTION_SSL_REJECT_UNAUTHORIZED=false