且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-07 18:25:40

方法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/