擴展基礎類型的函數
interface String {
toBool: () => boolean;
}
String.prototype.toBool = function (): boolean {
return this.valueOf() === '1' || this.valueOf().toUpperCase() === 'TRUE' || false;
}
其中 valueof() 取的纔是真實的string,而不是 this === ‘1’ ,this代表 {"1"} 對象;
另外,this == "1" 也可以實現toBool 的功能,內部實現了 {"1"} 轉換爲 "1",但是不推薦使用;
-----------------------------------------------------------------------------------------------------------------
其他:
判斷基礎類型:用 typeof(t) === "string" | "number" ...
var t = "1";
typeof(t) === "string" // true
typeof(t) === "String" // false