3 回答

TA貢獻1841條經驗 獲得超3個贊
您可以使用typeof運算符:
var booleanValue = true;
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"
此網頁中的示例。(盡管示例已稍作修改)。
在使用創建的字符串的情況下,這將無法正常工作new String(),但很少使用,建議在[1] [2]中使用。如果您愿意,請參閱其他答案以了解如何處理這些問題。
Google JavaScript樣式指南說永遠不要使用原始對象包裝器。
Douglas Crockford 建議不推薦使用原始對象包裝器。

TA貢獻1111條經驗 獲得超0個贊
這對我有效:
if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else
添加回答
舉報