如何證明一個變量是 String 類型?
| 方法 | 代碼示例 | 優點 | 缺點 |
|---|---|---|---|
| Object.prototype.toString.call() | | 最嚴謹,不可被繼承欺騙 | 代碼稍長 |
| typeof | typeof str === "string" | 簡潔,性能好 | 無法區分字符串對象 new String() |
| instanceof | str instanceof String | 能識別 String 對象 | 跨 iframe 失效,字面量返回 false |
| constructor | str.constructor === String | 直觀 | 可被篡改,不可靠 |
// 通用工具函數
function isString(value) {
return Object.prototype.toString.call(value) === "[object String]";
}
// 使用示例
console.log(isString("hello")); // true
console.log(isString(new String("hi"))); // true
console.log(isString(123)); // false
Object.prototype.toString 返回標準格式 [object [[Class]]],其中 [[Class]] 是內部屬性,ECMAScript 規範保證其不可篡改,因此是類型判斷的「金標準」。