js 验证是否是对象

2017-08-30 10:31:22 +08:00
 yantianqi
_.isObject = function (obj) {
        var type = typeof obj;
        return type === 'function' || type === 'object' && !!obj;
    };

判断是否是对象
其中!!obj是为了验证什么?

2455 次点击
所在节点    程序员
14 条回复
royzxq
2017-08-30 10:34:57 +08:00
null 也是 object.
Zegendary
2017-08-30 10:54:23 +08:00
typeof null === 'object' 所以你懂的
bombless
2017-08-30 11:08:14 +08:00
!!多余了
bombless
2017-08-30 11:08:50 +08:00
啊搞错,这里应该是有意返回布尔值
fulvaz
2017-08-30 11:12:25 +08:00
楼主在研究 lodash 吗?
learnshare
2017-08-30 11:24:55 +08:00
>typeof null
<"object"

>!null
<true

>!!null
<false

>!{}
<false

>!!{}
<true
dongliangnerd
2017-08-30 11:27:48 +08:00
为了排除 null,以为 typeof null === 'object'。应该是 underscore 的源码
autoxbc
2017-08-30 12:32:51 +08:00
这代码是有问题的,至少需要设定一个前提

一般不简单的说一个东西是否是对象,因为 js 里万物皆对象
最好说,基本类型,基本包装类型,引用类型

取决于你怎么看基本包装类型
typeof 可能并不可靠

typeof 123
// "number"
typeof new Number(123)
// "object"

框架里一般会用这个方法判断

Object.prototype.toString.call(123)
// "[object Number]"
Object.prototype.toString.call(new Number(123))
// "[object Number]"
dongliangnerd
2017-08-30 12:49:59 +08:00
@autoxbc 如果
dongliangnerd
2017-08-30 12:51:18 +08:00
@autoxbc
如果出现了 new Number(123) 才是最大的问题。
下面是 lodash 的源码
function isObject(value) {
const type = typeof value
return value != null && (type == 'object' || type == 'function')
}
zhlssg
2017-08-30 12:52:22 +08:00
所以直接用 tostring 好了,省了那么多坑
opengps
2017-08-30 12:57:48 +08:00
为啥不先搜搜,我就是刚学会了!!的意义,算是强制识别成 bool 类型
m31271n
2017-08-30 13:40:17 +08:00
`type === 'object' && !!obj` 是为了验证 obj 不是 `null`。刚好前阵子总结了一次 JS 的类型检测 https://blog.m31271n.com/2016/10/02/ES-%E5%9F%BA%E7%A1%80-%E2%80%94%E2%80%94-%E7%B1%BB%E5%9E%8B%E6%A3%80%E6%B5%8B/ ,希望对你有所帮助。
meepo3927
2017-08-30 14:22:29 +08:00
!! 强制转换成布尔型

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/386805

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX