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

时间:2018-08-25 13:33:26

标签: angular typescript angular-local-storage

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

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

app.component.ts

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

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

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中的

布尔值值;

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

谁能帮我解决这个问题。

7 个答案:

答案 0 :(得分:29)

方法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' ? true : false;   //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/

答案 1 :(得分:2)

我一直在尝试使用// 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)); 使用不同的值,并且似乎可以完成工作:

import React, {Component} from 'react';

export default class DropdownMenu extends Component {

    constructor(props) {
        super(props);

        this.state = {
            highlight: false,
            count: this.props.count || 0,
            selection: null
        }
        this.showDropdown = this.showDropdown.bind(this);
        this.selectItem = this.selectItem.bind(this);
    }

    componentDidMount() {

    }

    showDropdown() {

    }

    selectItem(e) {

    }

    render() {
        return <div className="dropdown__menu" onClick={this.props.onClick}>
            {this.props.text} {this.state.count > 0 ? <b>{this.state.count}</b> : ''}
            <div className="dropdown__content"
                 style={this.props.isOpen ? {'display': 'block'} : {'display': 'none'}}>
                {this.props.children}
            </div>
        </div>
    }
}

答案 2 :(得分:0)

在您的情况下,可以通过类似someString === 'true'的方式将字符串转换为布尔值(已回答)。

但是,让我尝试解决您的主要问题:处理本地存储。

本地存储仅支持将字符串用作值;因此,使用它的一种好方法是始终将数据序列化为字符串,然后再将其存储在存储器中,并在获取数据时逆转该过程。

用于序列化数据的一种可能不错的格式是JSON,因为它很容易用JavaScript处理。

因此,可以将以下功能与本地存储进行交互,前提是您的数据可以序列化为JSON。

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

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

您的示例可以重写为:

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

并且:

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

答案 3 :(得分:0)

定义扩展名: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
  }
}

并在要使用它的任何文件中导入“ @ / path / to / String + Extension”

答案 4 :(得分:0)

如果您知道字符串中的有效布尔值,您也可以尝试使用 bang bang 运算符。例如

let trueAsString = 'true';

let convertedStringToBool = !!trueAsString;

答案 5 :(得分:-2)

你可以使用它:

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

答案 6 :(得分:-4)

Boolean(“ true”)也可以做