最近在寫一些 JavaScript 的題目,才發現 JavaScript 中有些東西的型別實在是滿奇怪的,或是每個 library 或 framework 定義不同,實作出來的型別也會不同,所以稍微整理了一下在 JavaScript 中各種型別的判定。
1. Primitive Type
1.1 string
function isString(value) {
return typeof value === 'string'
}
1.2 number
function isNumber(value) {
return typeof value === 'number'
}
1.3 bigint
function isBigInt(value) {
return typeof value === 'bigint'
}
1.4 boolean
function isBoolean(value) {
return typeof value === 'boolean'
}
// or
function isBoolean(value) {
return value === true || value === false
}
1.5 undefined
function isUndefined(value) {
return typeof value === 'undefined'
}
// or
function isUndefined(value) {
return value === 'undefined'
}
1.6 symbol
function isSymbol(value) {
return typeof value === 'symbol'
}
1.7 null
function isNull(value) {
return value === null
}
// 注意:typeof null 會是 'object',不能用來判斷是不是 null
2. Non-Primitive Type
2.1 array
function isArray(value) {
return Array.isArray(value)
}
// 注意:typeof [] 會是 'object',不能用來判斷是不是 array
2.2 function
function isFunction(value) {
return typeof value === 'function'
}
2.3 object
- 這裡的 object 是指 JavaScript 中廣義的 object,包含:array, function, object,但不包含 null 和 undefined
function isObject(value) {
if (value == null) return false
return typeof value === 'object' || typeof value === 'function'
}
2.4 plain object
- 在 JavaScript 中,plain object 又稱為 Plain Old JavaScript Object - POJO
- object 透過
Object.create(null)
是為 plain object - object 的 prototype 和
Object.prototype
一樣,是為 plain object - 透過 class 建立的 object,不為 plain object
class Student(name) {
name
constructor(name) {
this.name = name
}
}
const student = new Student('Jimmy')
isPlainObject(student)
// false
- 透過 function 建立的 object,不為 plain object
function Student(name) {
this.name = name
}
const student = new Student('Jimmy')
isPlainObject(student)
// false
function isPlainObject(value) {
if (value == null) return false
const prototype = Object.getPrototypeOf(value)
// 透過 Object.create(null) 建立的 object,其 prototype 為 null
return prototype === Object.prototype || prototype === null
}
// 在某些框架或 library 中,class 和 function 建立的 object 也會算是 plain object,則可以用以下方法:
function isPlainObject(value) {
return Object.prototype.toString.call(value) === '[object Object]'
}
參考資料
typeof - JavaScript - MDN Web Docs - Mozilla
Type Utilities | JavaScript Interview Questions with Solutions
Type Utilities II | JavaScript Interview Questions with …
[筆記] JavaScript 中的Plain Object - Nono’s Blog