【问题标题】:How to convert a string to a boolean?如何将字符串转换为布尔值?
【发布时间】:2021-02-23 11:46:05
【问题描述】:
我正在从服务器检索一些信息,当通知打开时,我会说 settings.notificationOn = "T",而 settings.notificationOn = "F"。我想将它保存到一个布尔变量(通知:布尔)中。
我想在 ion-toggle 中使用这个变量,当 notify 为 true 时检查为 true,而 notify 为 false 时不检查。
我该怎么做?
谢谢
【问题讨论】:
标签:
angular
typescript
ionic-framework
【解决方案1】:
要确保notificationOn 没有任何错误值,您可以这样做:
const notify: boolean = this.getNotificationStatus(settings);
getNotificationStatus(settings: { notificationOn: 'T' | 'F' }): boolean {
if (settings.notificationOn === "T") return true;
if (settings.notificationOn === "F") return false;
throw new Error("/* Your error here */");
}
【解决方案2】:
如果 "T" 则为真,否则为假。
const notify: boolean = settings.notificationOn === "T" ? true : false;
【解决方案3】:
简单地做:
const notify: boolean = (settings.notificationOn === "T");
【解决方案4】:
你可以这样做:
notify: boolean = settings.notificationOn == "T" ? true : false ;
【解决方案5】:
如果它是一个包含 'F' 或 'T' 的字符串,那么您可以使用以下代码:
const notify = settings.notificationOn === 'T';
简短说明:
您正在将 settings.notificationOn 是否等于 'T' 的表达式的结果分配给 notify 变量。如果是,则 value 为 true,否则为 false。