js判斷資料型別
- typeof
- instanceof
- Object.prototype.toString
typeof
typeof 1 // number
typeof '2' // string
typeof true // boolean
typeof undefined // undefined
typeof null // object
typeof [1, 2] // object
typeof {} // object
typeof function fun() {} // function
可以發現,此方法可以判斷大部分資料型別,但是當遇見null 和陣列的時候不準確
instanceof
instanceof運算子用來驗證,一個物件是否為指定的建構式的實體
[] instanceof Object // true
[] instanceof Array // true
{} instanceof Object // true
Promise.resolve() instanceof Promise // true
不能分別出 Object和 Array
Object.prototype.toString
利用Object.prototype上的 toString 方法,回傳字串
[1, '2', true, undefined, null, [1, 2], {}, function () {}].forEach(
(item) => {
console.log(Object.prototype.toString.call(item))
}
)
/*
[object Number]
[object String]
[object Boolean]
[object Undefined]
[object Null]
[object Array]
[object Object]
[object Function]
*/
然后截取字串得到最后的值
[1, '2', true, undefined, null, [1, 2], {}, function () {}].forEach(
(item) => {
let str = Object.prototype.toString.call(item)
console.log(str.slice(8, -1))
}
)
/*
Number
String
Boolean
Undefined
Null
Array
Object
Function
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/296964.html
標籤:其他
上一篇:自定義中間件生成token
