Home > Web Front-end > JS Tutorial > body text

How to determine whether it is an object in javascript

青灯夜游
Release: 2023-01-03 09:31:53
Original
17783 people have browsed it

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]'
Copy after login

2. constructor

let obj = {}
obj.constructor === Object
Copy after login

【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
Copy after login

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'
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template