Kev*_*vin 2328 javascript
我可以将表示布尔值的字符串(例如,'true','false')转换为JavaScript中的内部类型吗?
我有一个隐藏的HTML格式,根据用户在列表中的选择进行更新.此表单包含一些表示布尔值的字段,并使用内部布尔值进行动态填充.但是,一旦将此值放入隐藏的输入字段,它就会变成一个字符串.
我可以找到确定字段的布尔值的唯一方法,一旦将其转换为字符串,就要依赖于字符串表示的字面值.
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来实现这一目标?
gui*_*aps 3156
var isTrueSet = (myValue == 'true');
Run Code Online (Sandbox Code Playgroud)
您可以通过使用identity运算符(===)来更严格,当比较变量具有不同类型而不是相等运算符()时,它不会进行任何隐式类型转换==.
var isTrueSet = (myValue === 'true');
Run Code Online (Sandbox Code Playgroud)
您应该谨慎使用这两种方法来满足您的特定需求:
var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
Run Code Online (Sandbox Code Playgroud)
任何不是空字符串的字符串都将true使用它们进行评估.虽然它们是我能想到的关于布尔转换的最干净的方法,但我认为它们不是你想要的.
Luk*_*uke 643
这个高度支持的遗留答案在技术上是正确的,但只涵盖一个非常具体的场景,当你的字符串值是完全"true"或"false"(必须也是小写).
传递给下面这些函数的无效json字符串将引发异常.
原始答案:
怎么样?
JSON.parse("True".toLowerCase());
Run Code Online (Sandbox Code Playgroud)
或者使用jQuery
$.parseJSON("TRUE".toLowerCase());
Run Code Online (Sandbox Code Playgroud)
小智 211
stringToBoolean: function(string){
switch(string.toLowerCase().trim()){
case "true": case "yes": case "1": return true;
case "false": case "no": case "0": case null: return false;
default: return Boolean(string);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 164
我认为这很普遍:
if (String(a) == "true") ...
它会:
String(true) == "true" //returns true
String(false) == "true" //returns false
String("true") == "true" //returns true
String("false") == "true" //returns false
Run Code Online (Sandbox Code Playgroud)
Jar*_*ish 123
请记住匹配案例:
var isTrueSet = (myValue.toLowerCase() === 'true');
Run Code Online (Sandbox Code Playgroud)
此外,如果它是表单元素复选框,您还可以检测是否选中了复选框:
var isTrueSet = document.myForm.IS_TRUE.checked;
Run Code Online (Sandbox Code Playgroud)
假设如果选中它,则"set"等于true.这个评估为真/假.
Sha*_*531 113
您可以使用正则表达式:
/*
* Converts a string to a bool.
*
* This conversion will:
*
* - match 'true', 'on', or '1' as true.
* - ignore all white-space padding
* - ignore capitalization (case).
*
* ' tRue ','ON', and '1 ' will all evaluate as true.
*
*/
function strToBool(s)
{
// will match one and only one of the string 'true','1', or 'on' rerardless
// of capitalization and regardless off surrounding white-space.
//
regex=/^\s*(true|1|on)\s*$/i
return regex.test(s);
}
Run Code Online (Sandbox Code Playgroud)
如果你想扩展String类,你可以这样做:
String.prototype.bool = function() {
return strToBool(this);
};
alert("true".bool());
Run Code Online (Sandbox Code Playgroud)
对于那些想要扩展String对象以获得它的人(请参阅注释)但是担心可枚举性并且担心与扩展String对象的其他代码发生冲突:
Object.defineProperty(String.prototype, "com_example_bool", {
get : function() {
return (/^(true|1)$/i).test(this);
}
});
alert("true".com_example_bool);
Run Code Online (Sandbox Code Playgroud)
(当然,在旧浏览器中不起作用,而Firefox显示错误,而Opera,Chrome,Safari和IE显示为真.错误720760)
Ste*_*ger 47
木眼要小心.在使用500多个upvotes应用最佳答案后看到后果后,我觉得有义务发布实际有用的内容:
让我们从最短但非常严格的方式开始:
var str = "true";
var mybool = JSON.parse(str);
Run Code Online (Sandbox Code Playgroud)
并以适当,更宽容的方式结束:
var parseBool = function(str)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
return false;
if (typeof str === 'boolean')
{
return (str === true);
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Run Code Online (Sandbox Code Playgroud)
测试:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
Run Code Online (Sandbox Code Playgroud)
Jan*_*nda 33
使用JSON解析的通用解决方案:
function getBool(val) {
return !!JSON.parse(String(val).toLowerCase());
}
getBool("1"); //true
getBool("0"); //false
getBool("true"); //true
getBool("false"); //false
getBool("TRUE"); //true
getBool("FALSE"); //false
Run Code Online (Sandbox Code Playgroud)
更新(没有JSON):
function getBool(val){
var num = +val;
return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,'');
}
Run Code Online (Sandbox Code Playgroud)
我还创建了小提琴来测试它http://jsfiddle.net/remunda/2GRhG/
BrD*_*aHa 32
我认为@Steven的答案是最好的,并且比传入的值只是一个字符串更能处理更多的情况.我想延长一点,并提供以下内容:
function isTrue(value){
if (typeof(value) === 'string'){
value = value.trim().toLowerCase();
}
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
false如果您已经知道所有true必须考虑的案例,则没有必要涵盖所有案例.您可以将任何内容传递给此方法,该方法可以传递true值(或者添加其他值,它非常简单),其他所有内容都会被考虑false
Jon*_*nan 30
你的解决方案很好.
===在这种情况下使用只是愚蠢,因为该领域value永远是一个String.
Pre*_*aul 22
var falsy = /^(?:f(?:alse)?|no?|0+)$/i;
Boolean.parse = function(val) {
return !falsy.test(val) && !!val;
};
Run Code Online (Sandbox Code Playgroud)
这将返回false对每falsy值和true对于不同的是每truthy值'false','f','no','n',和'0'(不区分大小写).
// False
Boolean.parse(false);
Boolean.parse('false');
Boolean.parse('False');
Boolean.parse('FALSE');
Boolean.parse('f');
Boolean.parse('F');
Boolean.parse('no');
Boolean.parse('No');
Boolean.parse('NO');
Boolean.parse('n');
Boolean.parse('N');
Boolean.parse('0');
Boolean.parse('');
Boolean.parse(0);
Boolean.parse(null);
Boolean.parse(undefined);
Boolean.parse(NaN);
Boolean.parse();
//True
Boolean.parse(true);
Boolean.parse('true');
Boolean.parse('True');
Boolean.parse('t');
Boolean.parse('yes');
Boolean.parse('YES');
Boolean.parse('y');
Boolean.parse('1');
Boolean.parse('foo');
Boolean.parse({});
Boolean.parse(1);
Boolean.parse(-1);
Boolean.parse(new Date());
Run Code Online (Sandbox Code Playgroud)
thd*_*oan 18
Boolean对象没有'parse'方法.Boolean('false')返回true,这样就行不通了.!!'false'也返回true,这样也行不通.
如果你想让string 'true'返回布尔值true而字符串'false'返回布尔值false,那么最简单的解决方案是使用eval().eval('true')返回true并eval('false')返回false.请记住使用时的性能影响eval().
zob*_*ier 15
我使用以下内容:
function parseBool(b) {
return !(/^(false|0)$/i).test(b) && !!b;
}
Run Code Online (Sandbox Code Playgroud)
此函数执行通常的布尔强制,但字符串"false"(不区分大小写)和"0"除外.
Fri*_*ich 14
我很惊讶includes没有建议
let bool = "false"
bool = !["false", "0", 0].includes(bool)
Run Code Online (Sandbox Code Playgroud)
您可以修改 true 的检查或包含更多条件(例如null, '')。
Tho*_*ing 13
Boolean.parse = function (str) {
switch (str.toLowerCase ()) {
case "true":
return true;
case "false":
return false;
default:
throw new Error ("Boolean.parse: Cannot convert string to boolean.");
}
};
Run Code Online (Sandbox Code Playgroud)
And*_*zsa 13
你正在寻找的表达方式就是
/^true$/i.test(myValue)
Run Code Online (Sandbox Code Playgroud)
如在
var isTrueSet = /^true$/i.test(myValue);
Run Code Online (Sandbox Code Playgroud)
这将myValue针对正则表达式进行测试,不区分大小写,并且不会修改原型.
例子:
/^true$/i.test("true"); // true
/^true$/i.test("TRUE"); // true
/^true$/i.test("tRuE"); // true
/^true$/i.test(" tRuE"); // false (notice the space at the beginning)
/^true$/i.test("untrue"); // false (some other solutions here will incorrectly return true
/^true$/i.test("false");// returns false
/^true$/i.test("xyz"); // returns false
Run Code Online (Sandbox Code Playgroud)
Hak*_*tık 13
这是从已接受的答案中取得的,但实际上它有一个非常弱点,我很震惊它是如何得到那些upvotes,它的问题,你必须考虑字符串的情况,因为这是区分大小写
var isTrueSet = (myValue.toLowerCase() === 'true');
Run Code Online (Sandbox Code Playgroud)
Moh*_*ani 13
you can use JSON.parse as follows:
var trueOrFalse='True';
result =JSON.parse(trueOrFalse.toLowerCase());
if(result==true)
alert('this is true');
else
alert('this is false');Run Code Online (Sandbox Code Playgroud)
in this case .toLowerCase is important
San*_*mal 11
已经有很多答案可供选择.但在某些情况下,以下内容可能很有用.
// One can specify all values against which you consider truthy
var TRUTHY_VALUES = [true, 'true', 1];
function getBoolean(a) {
return TRUTHY_VALUES.some(function(t) {
return t === a;
});
}
Run Code Online (Sandbox Code Playgroud)
当一个示例具有非布尔值时,这可能很有用.
getBoolean('aa'); // false
getBoolean(false); //false
getBoolean('false'); //false
getBoolean('true'); // true
getBoolean(true); // true
getBoolean(1); // true
Run Code Online (Sandbox Code Playgroud)
Fel*_*aro 11
使用逻辑 NOT两次[ !! ]获取转换后的字符串
把这个表情贴上...
const stringToBoolean = (string) => string === 'false' ? false : !!string
Run Code Online (Sandbox Code Playgroud)
并将您的字符串传递给它!
stringToBoolean('') // false
stringToBoolean('false') // false
stringToBoolean('true') // true
stringToBoolean('hello my friend!') // true
Run Code Online (Sandbox Code Playgroud)
奖金!
const betterStringToBoolean = (string) =>
string === 'false' || string === 'undefined' || string === 'null' || string === '0' ?
false : !!string
Run Code Online (Sandbox Code Playgroud)
您可以随意包含其他字符串以轻松扩展此表达式的用法...:
betterStringToBoolean('undefined') // false
betterStringToBoolean('null') // false
betterStringToBoolean('0') // false
betterStringToBoolean('false') // false
betterStringToBoolean('') // false
betterStringToBoolean('true') // true
betterStringToBoolean('anything else') // true
Run Code Online (Sandbox Code Playgroud)
Fiz*_*han 10
将字符串("true","false")和布尔值都转换为布尔值
('' + flag) === "true"
Run Code Online (Sandbox Code Playgroud)
哪里flag可以
var flag = true
var flag = "true"
var flag = false
var flag = "false"
Run Code Online (Sandbox Code Playgroud)
你为什么不尝试这样的事情
Boolean(JSON.parse((yourString.toString()).toLowerCase()));
Run Code Online (Sandbox Code Playgroud)
当给出一些其他文本而不是真或假时,它将返回错误,无论情况如何,它也将捕获数字
// 0-> false
// any other number -> true
Run Code Online (Sandbox Code Playgroud)
小智 9
此函数可以处理字符串以及布尔值true/false.
function stringToBoolean(val){
var a = {
'true':true,
'false':false
};
return a[val];
}
Run Code Online (Sandbox Code Playgroud)
演示如下:
function stringToBoolean(val) {
var a = {
'true': true,
'false': false
};
return a[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("=============================================");
// what if value was undefined?
console.log("undefined result: " + stringToBoolean(undefined));
console.log("type of undefined result: " + typeof(stringToBoolean(undefined)));
console.log("=============================================");
// what if value was an unrelated string?
console.log("unrelated string result: " + stringToBoolean("hello world"));
console.log("type of unrelated string result: " + typeof(stringToBoolean(undefined)));Run Code Online (Sandbox Code Playgroud)
小智 8
放下最简单的方法(假设你的字符串是'true'或'false')是:
var z = 'true';
var y = 'false';
var b = (z === 'true'); // will evaluate to true
var c = (y === 'true'); // will evaluate to false
Run Code Online (Sandbox Code Playgroud)
对于这些类型的转换,始终使用===运算符而不是==运算符!
小智 8
就像@ Shadow2531所说,你不能直接转换它.我还建议你考虑字符串输入,除了"真实"和"假",如果你的代码将被其他人重用/使用,那么它们是"真实的"和"虚假的".这是我使用的:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用这个
String.prototype.maybeBool = function(){
if ( ["yes", "true", "1", "on"].indexOf( this.toLowerCase() ) !== -1 ) return true;
if ( ["no", "false", "0", "off"].indexOf( this.toLowerCase() ) !== -1 ) return false;
return this;
}
"on".maybeBool(); //returns true;
"off".maybeBool(); //returns false;
"I like js".maybeBool(); //returns "I like js"
Run Code Online (Sandbox Code Playgroud)
您需要(在您的思考中)分离您的选择的值和该值的表示.
在JavaScript逻辑中选择一个点,它们需要从字符串标记转换为本机类型并在那里进行比较,最好只需要为每个需要转换的值完成一次.如果字符串sentinel不是脚本知道的那个(即你默认为true还是false?),请记住要解决需要发生的事情.
换句话说,是的,您需要依赖字符串的值.:-)
我对这个问题的看法是,它旨在满足三个目标:
使用JSON的问题在于它因导致Javascript错误而失败.这个解决方案不具备弹性(尽管它满足1和3):
JSON.parse("FALSE") // fails
Run Code Online (Sandbox Code Playgroud)
这个解决方案不够简洁:
if(value === "TRUE" || value === "yes" || ...) { return true; }
Run Code Online (Sandbox Code Playgroud)
我正在努力为Typecast.js解决这个确切的问题.这三个目标的最佳解决方案是:
return /^true$/i.test(v);
Run Code Online (Sandbox Code Playgroud)
它适用于许多情况,在传递{}之类的值时不会失败,并且非常简洁.它还返回false作为默认值而不是undefined或抛出Error,这在松散类型的Javascript开发中更有用.Bravo到其他建议的答案!
我有点晚了,但我有一个小片段来做到这一点,它本质上维护所有JScripts的truthey/falsey/肮脏 -ness但包括"false"作为虚假的acceptible值.
我更喜欢这种方法,因为它不依赖于第三方来解析代码(即:eval/JSON.parse),这在我看来是过度的,它足够短,不需要实用功能并维护其他truthey/falsey惯例.
var value = "false";
var result = (value == "false") != Boolean(value);
// value = "true" => result = true
// value = "false" => result = false
// value = true => result = true
// value = false => result = false
// value = null => result = false
// value = [] => result = true
// etc..
Run Code Online (Sandbox Code Playgroud)
另一种方案. 的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
};
Run Code Online (Sandbox Code Playgroud)
测试用例在节点中运行
> 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
>
Run Code Online (Sandbox Code Playgroud)
function isTrue(val) {
try {
return !!JSON.parse(val);
} catch {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
我一直使用的最简单的方法:
let value = 'true';
let output = value === 'true';
Run Code Online (Sandbox Code Playgroud)
const boolTrue = JSON.parse("true")
const boolFalse = JSON.parse("false")
console.log(boolTrue) // true
console.log(boolFalse) // falseRun Code Online (Sandbox Code Playgroud)
要将像“true”这样的字符串布尔值转换为实际的布尔值,只需包装到JSON.parse()
示例:JSON.parse("true")
这是我最近遇到的最简单的布尔转换方法。想加了。
JSON.parse('true');
Run Code Online (Sandbox Code Playgroud)
JSON.parse('true');
Run Code Online (Sandbox Code Playgroud)
最佳性能根据/sf/answers/2001184111/
输入我在所有其他答案中没有看到的安全且严格的答案(如果您想对输入执行更严格的规则,那就太好了),当它得到不正确的输入时,还会在控制台中为您提供清晰的解释:
打字稿版本:
function parseBool(value: any):boolean {
if (value === 'true') return true
if (value === 'false') return false
console.error('parseBool got an unexpected value:', value, '(accepted values : "true", "false")')
throw new Error('Error: parseBool got unexpected value')
}
Run Code Online (Sandbox Code Playgroud)
箭头函数版本:
const parseBool = (value: any):boolean => {
if (value === 'true') return true
if (value === 'false') return false
console.error('parseBool got an unexpected value:', value, '(accepted values : "true", "false")')
throw new Error('Error: parseBool got unexpected value')
}
Run Code Online (Sandbox Code Playgroud)
JavaScript 版本:
function parseBool(value){
if (value === 'true') return true
if (value === 'false') return false
console.error('parseBool got an unexpected value:', value, '(accepted values : "true", "false")')
throw new Error('Error: parseBool got unexpected value')
}
Run Code Online (Sandbox Code Playgroud)
function parseBool(value) {
if (typeof value === "boolean") return value;
if (typeof value === "number") {
return value === 1 ? true : value === 0 ? false : undefined;
}
if (typeof value != "string") return undefined;
return value.toLowerCase() === 'true' ? true : false;
}
Run Code Online (Sandbox Code Playgroud)
我写了一个函数来匹配PHP的filter_var,这很好地完成了.主旨有:https://gist.github.com/CMCDragonkai/7389368
/**
* Parses mixed type values into booleans. This is the same function as filter_var in PHP using boolean validation
* @param {Mixed} value
* @param {Boolean} nullOnFailure = false
* @return {Boolean|Null}
*/
var parseBooleanStyle = function(value, nullOnFailure = false){
switch(value){
case true:
case 'true':
case 1:
case '1':
case 'on':
case 'yes':
value = true;
break;
case false:
case 'false':
case 0:
case '0':
case 'off':
case 'no':
value = false;
break;
default:
if(nullOnFailure){
value = null;
}else{
value = false;
}
break;
}
return value;
};
Run Code Online (Sandbox Code Playgroud)
我使用自己的方法,其中包括首先检查对象是否存在以及更直观地转换为布尔值:
function str2bool(strvalue){
return (strvalue && typeof strvalue == 'string') ? (strvalue.toLowerCase() == 'true' || strvalue == '1') : (strvalue == true);
}
Run Code Online (Sandbox Code Playgroud)
结果是:
var test; // false
var test2 = null; // false
var test3 = 'undefined'; // false
var test4 = 'true'; // true
var test5 = 'false'; // false
var test6 = true; // true
var test7 = false; // false
var test8 = 1; // true
var test9 = 0; // false
var test10 = '1'; // true
var test11 = '0'; // false
Run Code Online (Sandbox Code Playgroud)
小提琴: http: //jsfiddle.net/av5xcj6s/
这里有很多花哨的答案。真的很惊讶没有人发布这个解决方案:
var booleanVal = toCast > '';
Run Code Online (Sandbox Code Playgroud)
除了 bool false、数字零和空字符串(显然)之外,这在大多数情况下解析为 true。您可以在事后轻松查找其他虚假字符串值,例如:
var booleanVal = toCast > '' && toCast != 'false' && toCast != '0';
Run Code Online (Sandbox Code Playgroud)
我们只需要考虑"false"字符串,因为任何其他字符串(包括"true")已经存在true.
function b(v){ return v==="false" ? false : !!v; }
Run Code Online (Sandbox Code Playgroud)
测试
b(true) //true
b('true') //true
b(false) //false
b('false') //false
Run Code Online (Sandbox Code Playgroud)
function bool(v){ return v==="false" || v==="null" || v==="NaN" || v==="undefined" || v==="0" ? false : !!v; }
Run Code Online (Sandbox Code Playgroud)
测试
bool(true) //true
bool("true") //true
bool(1) //true
bool("1") //true
bool("hello") //true
bool(false) //false
bool("false") //false
bool(0) //false
bool("0") //false
bool(null) //false
bool("null") //false
bool(NaN) //false
bool("NaN") //false
bool(undefined) //false
bool("undefined") //false
bool("") //false
bool([]) //true
bool({}) //true
bool(alert) //true
bool(window) //true
Run Code Online (Sandbox Code Playgroud)
String(true).toLowerCase() == 'true'; // true
String("true").toLowerCase() == 'true'; // true
String("True").toLowerCase() == 'true'; // true
String("TRUE").toLowerCase() == 'true'; // true
String(false).toLowerCase() == 'true'; // false
Run Code Online (Sandbox Code Playgroud)
如果您不确定输入,则上述适用于布尔值以及任何字符串.
神圣的一些这些答案只是疯狂的.我喜欢JS及其无数种方法来涂抹bool.
我不喜欢看到的我的偏好是:
testVar = testVar.toString().match(/^(true|[1-9][0-9]*|[0-9]*[1-9]+|yes)$/i) ? true : false;
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您确定测试主题始终是一个字符串,那么明确检查它true是否等于是您最好的选择。
您可能需要考虑包含一些额外的代码,以防万一主题实际上可能是布尔值。
var isTrueSet =
myValue === true ||
myValue != null &&
myValue.toString().toLowerCase() === 'true';
Run Code Online (Sandbox Code Playgroud)
如果代码得到改进/重构以使用实际的布尔值而不是字符串,这可以在将来为您节省一些工作。
小智 5
最简单的方法是
a = 'True';
a = !!a && ['1', 'true', 1, true].indexOf(a.toLowerCase()) > -1;
Run Code Online (Sandbox Code Playgroud)
/// Convert something to boolean
function toBoolean( o ) {
if ( null !== o ) {
let t = typeof o;
if ( "undefined" !== typeof o ) {
if ( "string" !== t ) return !!o;
o = o.toLowerCase().trim();
return "true" === o || "1" === o;
}
}
return false;
}
toBoolean(false) --> false
toBoolean(true) --> true
toBoolean("false") --> false
toBoolean("true") --> true
toBoolean("TRue") --> true
toBoolean("1") --> true
toBoolean("0") --> false
toBoolean(1) --> true
toBoolean(0) --> false
toBoolean(123.456) --> true
toBoolean(0.0) --> false
toBoolean("") --> false
toBoolean(null) --> false
toBoolean() --> false
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1808485 次 |
| 最近记录: |