简体   繁体   English

如何在打字稿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);

here this.btnLoginNumOne and this.btnLoginEdit are string values ("true,false") .这里this.btnLoginNumOnethis.btnLoginEdit是字符串值("true,false")

mirror.component.ts镜像.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
}

in this component this.btnLoginNumOn e and this.btnLoginEdi t are Boolean values;在这个组件中this.btnLoginNumOn e 和this.btnLoginEdi t 是布尔值;

I tried the solutions in stackoverflow but nothing is worked.我尝试了stackoverflow中的解决方案,但没有任何效果。

Can anyone help me to fix this .谁能帮我解决这个问题。

Method 1 :方法一:

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

Method 2 :方法二:

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

Method 3 :方法3:

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

Method 4 :方法四:

var stringValue = "true";
var boolValue = stringValue.toLowerCase() == 'true'; //returns true

Method 5 :方法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;
    }
}

source:http://codippa.com/how-to-convert-string-to-boolean-javascript/来源:http ://codippa.com/how-to-convert-string-to-boolean-javascript/

I have been trying different values with JSON.parse(value) and it seems to do the work:我一直在尝试使用JSON.parse(value)不同的值,它似乎可以完成工作:

// true
Boolean(JSON.parse("true"));
Boolean(JSON.parse("1"));
Boolean(JSON.parse(1));
Boolean(JSON.parse(true));

// false
Boolean(JSON.parse("0")); 
Boolean(JSON.parse(0));
Boolean(JSON.parse("false"));
Boolean(JSON.parse(false));

In your scenario, converting a string to a boolean can be done via something like someString === 'true' (as was already answered).在您的场景中,可以通过someString === 'true'类的方法将字符串转换为布尔值(正如已经回答的那样)。

However, let me try to address your main issue: dealing with the local storage.但是,让我尝试解决您的主要问题:处理本地存储。

The local storage only supports strings as values;本地存储只支持字符串作为值; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.因此,使用它的一种好方法是始终将数据序列化为字符串,然后再将其存储在存储中,并在获取数据时反转该过程。

A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.序列化数据的一种可能不错的格式是 JSON,因为它在 JavaScript 中很容易处理。

The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.因此,如果您的数据可以序列化为 JSON,则可以使用以下函数与本地存储进行交互。

function setItemInStorage(key, item) {
  localStorage.setItem(key, JSON.stringify(item));
}

function getItemFromStorage(key) {
  return JSON.parse(localStorage.getItem(key));
}

Your example could then be rewritten as:然后可以将您的示例重写为:

setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);

And:和:

const pageLoadParams = getItemFromStorage('CheckOutPageReload');
if (pageLoadParams) {
  this.btnLoginNumOne = pageLoadParams[0];
  this.btnLoginEdit = pageLoadParams[1];
}

Define extension: String+Extension.ts定义扩展:String+Extension.ts

interface String {
  toBoolean(): boolean
}

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

And import in any file where you want to use it '@/path/to/String+Extension'并导入您要使用它的任何文件'@/path/to/String+Extension'

This function will convert your string to boolean此函数会将您的字符串转换为布尔值

export const stringToBoolean = (str: string | null | undefined) => {
    if (!str) {
        return false
    }
    if (typeof str === "string") {
        return !["0", "false", "no", "n", "null", "undefined", "nil"].includes(str.toLowerCase().trim())
    }
    return Boolean(str)
}

I think this is most accurate:我认为这是最准确的:

function parseBoolean(value?: string | number | boolean | null) {
    value = value?.toString().toLowerCase();
    return value === 'true' || value === '1';
}

just use << !!只需使用 << !! >> operator: >> 运算符:

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

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

You can use that:你可以使用它:

let s: string = "true";
let b: boolean = Boolean(s);

You could also try using the bang bang operator if you know its a valid boolean value in the string.如果您知道字符串中的有效布尔值,您也可以尝试使用 bang bang 运算符。 for eg例如

let trueAsString = 'true';

let convertedStringToBool = !!trueAsString;

Boolean("true") 也可以完成这项工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM