javaScript 中如何檢測一個變量是一個 String 類型?

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判斷數據類型,只能區分基本類型,即:numberstringundefinedbooleanobject。 對於nullarrayfunctionobject來說,使用typeof都會統一返回object字符串。 要想區分對象、數組、函數、單純使用typeof是不行的。在JS中,可以通過Object.prototype.toString方法,判斷某個對象之屬於哪種內置類型。 分爲nullstringbooleannumberundefinedarrayfunctionobjectdatemath

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]"

 

發佈了24 篇原創文章 · 獲贊 8 · 訪問量 5195
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章