如何在打字稿Angular 4中将字符串转换为布尔值

新手上路,请多包涵

我知道不是第一个问这个问题的人,正如我在标题中提到的,我正在尝试将字符串值转换为布尔值。

我之前已经将一些值放入本地存储,现在我想获取所有值并将所有值分配给一些布尔变量。

app.component.ts

 localStorage.setItem('CheckOutPageReload', this.btnLoginNumOne + ',' + this.btnLoginEdit);

这里 this.btnLoginNumOnethis.btnLoginEdit 是字符串值 (“true,false”)

镜像.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 是 布尔 值;

我尝试了stackoverflow中的解决方案,但没有任何效果。

谁能帮我解决这个问题。

原文由 Zhu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 560
2 个回答

方法一:

 var stringValue = "true";
var boolValue = (/true/i).test(stringValue) //returns true

方法二:

 var stringValue = "true";
var boolValue = (stringValue =="true");   //returns true

方法3:

 var stringValue = "true";
var boolValue = JSON.parse(stringValue);   //returns true

方法四:

 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/

原文由 Ayoub k 发布,翻译遵循 CC BY-SA 4.0 许可协议

只需使用 << !! >> 运算符:

 const Text1 = ""
const Text2 = "there is a text"

console.log(!!Text1) // false
console.log(!!Text2) // true

原文由 Chadjaa Sofianne 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进