您的位置:首页 > 技术中心 > 前端框架 >

javascript怎么判断是否为对象

时间:2021-03-30 20:01

判断方法:1、使用toString()来判断;2、使用“obj.constructor === Object”来判断;3、使用“ypeof obj === Object”来判断;4、利用instanceof关键字来判断。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

1、toString() 第一选择

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

2、constructor

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

【推荐学习:js基础教程】

3、instanceof

注意:使用instanceof对数组进行判断也是对象

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'

更多编程相关知识,请访问:编程视频!!

以上就是javascript怎么判断是否为对象的详细内容,更多请关注www.gxlsystem.com其它相关文章!

本类排行

今日推荐

热门手游