如何在打字稿Angular 4中将字符串转换为布尔值 [英] How to convert string to boolean in typescript Angular 4
问题描述
我知道不是第一个提出这个问题的人,正如我在标题中提到的那样,我正在尝试将字符串值转换为布尔值.
I know am not the first to ask this and as I mentioned in my title ,I am trying to convert string value boolean .
我以前已经将一些值放入本地存储中,现在我想获取所有值并将所有值分配给一些布尔变量.
I have previously put some values into local storage,Now I want to get all the values and assign all to the some boolean variables .
app.component.ts
app.component.ts
localStorage.setItem('CheckOutPageReload', this.btnLoginNumOne + ',' + this.btnLoginEdit);
此处this.btnLoginNumOne
和this.btnLoginEdit
是字符串值("true,false").
mirror.component.ts
mirror.component.ts
if (localStorage.getItem('CheckOutPageReload')) {
let stringToSplit = localStorage.getItem('CheckOutPageReload');
this.pageLoadParams = stringToSplit.split(',');
this.btnLoginNumOne = this.pageLoadParams[0]; //here I got the error as boolean value is not assignable to string
this.btnLoginEdit = this.pageLoadParams[1]; //here I got the error as boolean value is not assignable to string
}
该组件中的
this.btnLoginNumOn
e和this.btnLoginEdi
t是布尔值值;
in this component this.btnLoginNumOn
e and this.btnLoginEdi
t are Boolean values;
我尝试了stackoverflow中的解决方案,但没有任何效果.
I tried the solutions in stackoverflow but nothing is worked.
谁能帮我解决这个问题.
Can anyone help me to fix this .
推荐答案
方法1:
var stringValue = "true";
var boolValue = (/true/i).test(stringValue) //returns true
方法2:
var stringValue = "true";
var boolValue = (stringValue =="true"); //returns true
方法3:
var stringValue = "true";
var boolValue = JSON.parse(stringValue); //returns true
方法4:
var stringValue = "true";
var boolValue = stringValue.toLowerCase() == 'true'; //returns true
方法5:
var stringValue = "true";
var boolValue = getBoolean(stringValue); //returns true
function getBoolean(value){
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
来源: http://codippa.com/how-to -convert-string-to-boolean-javascript/
这篇关于如何在打字稿Angular 4中将字符串转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!