檢測資料型別的經典方法

2021-09-22 22:45:59 字數 2813 閱讀 3145

用 typeof 是否能準確判斷乙個物件變數,答案是否定的,null 的結果也是 object,陣列的結果也是 object,有時候我們需要的是 「純粹」 的 object 物件。如何避免呢?比較好的方式是:

console.

log(object.prototype.tostring.

call

(obj)

==="[object object]"

);

console.

log(object.prototype.tostring.

call

("jerry"))

;//[object string]

console.

log(object.prototype.tostring.

call(12

));//[object number]

console.

log(object.prototype.tostring.

call

(true))

;//[object boolean]

console.

log(object.prototype.tostring.

call

(undefined));

//[object undefined]

console.

log(object.prototype.tostring.

call

(null))

;//[object null]

console.

log(object.prototype.tostring.

call()

);//[object object]

console.

log(object.prototype.tostring.

call

(function()

));//[object function]

console.

log(object.prototype.tostring.

call([

]));

//[object array]

console.

log(object.prototype.tostring.

call

(new

date))

;//[object date]

console.

log(object.prototype.tostring.

call

(/\d/))

;//[object regexp]

function

person()

;console.

log(object.prototype.tostring.

call

(new

person))

;//[object object]

tostring方法返回反映這個物件的字串,所以能準確區分資料型別

那為什麼不直接用obj.tostring()呢?看一段**

console.

log(

"jerry"

.tostring()

);//jerry

console.

log((1

).tostring()

);//1console.

log([1

,2].

tostring()

);//1,2

console.

log(

newdate()

.tostring()

);//wed dec 21 2016 20:35:48 gmt+0800 (中國標準時間)

console.

log(

function()

.tostring()

);//function (){}

console.

log(

null

.tostring()

);//error

console.

log(undefined.

tostring()

);//error

同樣是檢測物件obj呼叫tostring方法(關於tostring()方法的用法的可以參考tostring的詳解),obj.tostring()的結果和object.prototype.tostring.call(obj)的結果不一樣,這是為什麼?

這是因為tostring為object的原型方法,而array 、function等型別作為object的例項,都重寫了tostring方法。不同的物件型別呼叫tostring方法時,根據原型鏈的知識,呼叫的是對應的重寫之後的tostring方法(function型別返回內容為函式體的字串,array型別返回元素組成的字串…),而不會去呼叫object上原型tostring方法(返回物件的具體型別),所以採用obj.tostring()不能得到其物件型別,只能將obj轉換為字串型別;因此,在想要得到物件的具體型別時,應該呼叫object上原型tostring方法

下面是乙個使用demo

const

istype

=(target,type)

=>

]` === typestring

} console.

log(

istype([

],'array'))

//true

該部落格僅為記錄開發中一些遇到的問題及解決方案,後續還會繼續更新維護。

關於檢測資料型別的方法

1 typeof用來檢測資料型別的運算子 依據上圖清晰可見typeof檢測資料型別包括 number string undefined function object typeof資料監測侷限性 typeof null object 不能具體細分是陣列還是正則,還是物件中其他值,因為使用typeof...

檢測資料型別

js中檢測資料型別只有四種方式 1 typeof 用來檢測資料型別的運算子 typeof value 1 返回值 首先是乙個字串,然後包含了我們常用的資料型別,例 如 number string boolean undefined object function typeof typeof type...

Python檢測資料型別的方法總結

我們在用python進行程式開發的時候,很多時候我們需要檢測一下當前的變程式設計客棧量的資料型別。比如需要在使用字串操作函式之前先檢測一下當前變數是否是字串。下面小編給大家分享一下在python中如何檢測資料型別 首先我們開啟cmd控制台,進入到python環境,然後宣告乙個列表,如下圖所示 然後我...