javaScript 中如何檢測一個變量是一個 String 類型?
答案:三種方法(typeof、constructor、Object.prototype.toString.call())
1.你可以使用 typeof 操作符來檢測變量的數據類型。
-
typeof運算符的返回類型爲字符串,值包括如下幾種:
-
'undefined' --未定義的變量或值
-
'boolean' --布爾類型的變量或值
-
'string' --字符串類型的變量或值
-
'number' --數字類型的變量或值
-
'object' --對象類型的變量或值,或者null(這個是js歷史遺留問題,將null作爲object類型處理)
-
'function' --函數類型的變量或值
typeof是一個運算符,有2種使用方式:typeof(表達式)和typeof 變量名,第一種是對表達式做運算,第二種是對變量做運算。
-
typeof('123') === "string" // true
typeof '123' === "string" // true
2.constructor 屬性返回對創建此對象的數組函數的引用。
<script type="text/javascript">
var test=new Array();
if (test.constructor==Array)
{
document.write("This is an Array");
}
if (test.constructor==Boolean)
{
document.write("This is a Boolean");
}
if (test.constructor==Date)
{
document.write("This is a Date");
}
if (test.constructor==String)
{
document.write("This is a String");
}
'123'.constructor === String // true
</script>
3.Object.prototype.toString.call()
Object.prototype.toString.call('123') === '[object String]' // true
在JavaScript
裏使用typeof
判斷數據類型,只能區分基本類型,即:number
、string
、undefined
、boolean
、object
。 對於null
、array
、function
、object
來說,使用typeof
都會統一返回object
字符串。 要想區分對象、數組、函數、單純使用typeof
是不行的。在JS中,可以通過Object.prototype.toString
方法,判斷某個對象之屬於哪種內置類型。 分爲null
、string
、boolean
、number
、undefined
、array
、function
、object
、date
、math
。
Object.prototype.toString.call(``null``); ``// "[object Null]"
Object.prototype.toString.call(undefined); ``// "[object Undefined]"
Object.prototype.toString.call(“abc”);``// "[object String]"
Object.prototype.toString.call(123);``// "[object Number]"
Object.prototype.toString.call(``true``);``// "[object Boolean]"