0
2

クラス属性を取得する

Posted at
Object.prototype.toString.call([])     // [object Array]
Object.prototype.toString.call(/./)    // [object RegExp]
Object.prototype.toString.call(()=>{}) // [object Function]

JavaScriptオブジェクトに対してクラス属性を取得するには、上記のObject.prototype.toString.call()を使用します。ですが、この方法以外では取得できない型情報が含まれています。typeof演算子ではオブジェクトの型を区別しないので、下記に作成したclassof()関数の方が便利です。

function classof(o) {
  return Object.prototype.toString.call(o).slice(8, -1);
}

classof(null)      // Null
classof(undefined) // Undefined
classof(6)         // Number
classof(10n**100n) // BigInt
classof('Hello')   // String
classof(false)     // Boolean
classof(Symbol())  // Symbol
classof({})        // Object
classof([])        // Array
classof(/./)       // RegExp
classof(()=>{})    // Function
classof(new Map()) // Map
classof(new Set()) // Set
classof(new Date())// Date

参考

0
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2