js基礎類型的擴展 string 和 String

擴展基礎類型的函數

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章