Home  >  Article  >  Web Front-end  >  How to determine whether it is an object in javascript

How to determine whether it is an object in javascript

青灯夜游
青灯夜游Original
2021-03-30 17:29:2017766browse

Judgment method: 1. Use toString() to judge; 2. Use "obj.constructor === Object" to judge; 3. Use "ypeof obj === Object" to judge; 4. Use instanceof keyword to judge.

How to determine whether it is an object in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1. toString() first choice

let obj = {}
Object.prototype.toString.call(obj) === '[Object Object]'

2. constructor

let obj = {}
obj.constructor === Object

【Recommended learning: js basic tutorial

3. instanceof

Attention : Using instanceof to judge an array is also an object

let obj = {}
obj instanceof Object  //true
let arr = []
arr instanceof Object  //true

4, typeof

let obj = {}
typeof obj === Object
// 根据typeof判断对象也不太准确
表达式                       返回值
typeof undefined           'undefined'
typeof null                'object'
typeof true                'boolean'
typeof 123                 'number'
typeof "abc"               'string'
typeof function() {}       'function'
typeof {}                  'object'
typeof []                  'object'

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of How to determine whether it is an object in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn