首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 面試必備:判斷變量是否為 String 類型的三種方法

     編輯:程式設計綜合問答

面試題

如何證明一個變量是 String 類型?

方法對比

方法代碼示例優點缺點
Object.prototype.toString.call()
var str = "Sdasda";
var type = Object.prototype.toString.call(str);
if(type === "[object String]") {
    alert("是字符串");
}
最嚴謹,不可被繼承欺騙代碼稍長
typeoftypeof str === "string"簡潔,性能好無法區分字符串對象 new String()
instanceofstr instanceof String能識別 String 對象跨 iframe 失效,字面量返回 false
constructorstr.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 規範保證其不可篡改,因此是類型判斷的「金標準」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved