javascript 中的 obj.length === +obj.length
在很多地方的 underscore.js 源代码中,我都遇到过
if (obj.length === +obj.length)
有人可以解释一下,为什么他们使用它?
In underscore.js source in many places I came across
if (obj.length === +obj.length)
Can someone explain, why do they use it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是 if (typeof obj.length == 'number') 的另一种编写方式。他们为什么这样做,谁也说不准。可能是想以牺牲可读性为代价来变得聪明。不幸的是,这在当今并不太罕见......
尽管它可能是这样的,这样它可以通过压缩器进行更多压缩(YUI 压缩器、闭包编译器、UglifyJS 等):
(a.length==+a.length)
<强>对比(typeof a.length=='number')
按照他们的方式这样做,每个实例可以节省 5 个字节。
It's another way of writing
if (typeof obj.length == 'number')
. Why they do it that way, it's anyone's guess. Probably trying to be clever at the expense of readability. Which is not too uncommon these days, unfortunately...Although it might be so that it can be compressed more by minifiers (YUI Compressor, Closure Compiler, UglifyJS, etc):
(a.length===+a.length)
vs(typeof a.length=='number')
Doing it their way would save 5 bytes, each instance.
这测试
obj
的length
属性是否是一个数字。一元
+
运算符 将其操作数转换为数字,并且 严格相等运算符将结果与原始length
属性进行比较,而不执行类型强制。因此,只有当
obj.length
是实际数字(而不是可以转换为数字的字符串)时,表达式才会为true
。This tests if
obj
'slength
property is a number.The unary
+
operator converts its operand to a number, and the strict equality operator compares the result with the originallength
property without performing type coercion.Therefore, the expression will only be
true
ifobj.length
is an actual number (not e.g. a string that can be converted to a number).我认为他们测试 obj.length 是否为数字的主要原因是为了区分 obj 类型的对象与 [object Array] (它也适用于 String 和 Function 对象)。
[object Object] 没有长度属性。
所以如果
考虑
P.S.:IMO 它回答了“他们为什么使用它”问题的第二部分
I think the main reason they are testing if obj.length is a number - is to differentiate obj type of Object from [object Array] (it would work also with String and Function objects).
The [object Object] has no length property.
so if
regards
P.S.: IMO it answers the second part of the "why do they use it" question
+obj.length
将obj.length
转换为数字。我认为这是为了测试 obj.length 是否是一个数字。
+obj.length
turnobj.length
to number.I think this is to test whether
obj.length
is a number.