我可以在JavaScript中将表示布尔值的字符串(例如“true”、“false”)转换为内部类型吗?
我有一个隐藏的HTML表单,它根据用户在列表中的选择进行更新。此表单包含一些表示布尔值的字段,并用内部布尔值动态填充。但是,一旦将该值放入隐藏的输入字段,它就会变成字符串。
一旦字段转换为字符串,我唯一能找到的确定它的布尔值的方法就是依赖于它的字符串表示的文字值。
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
有没有更好的方法来实现这一点?
如果使用的是环境变量,请使用以下命令。在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
我编写了一个助手函数来处理您的案例(以及其他一些)。根据您的具体需要随意更改
/**
* @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);
};