JavaScript 或 underscore.js 中可能存在负对象长度吗?意义?
我正在查看 下划线的源代码。 js 库,专门用于 map 方法(该页面上第 85 行左右,并复制到此处):
_.map = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
if (obj.length === +obj.length) results.length = obj.length;
return results;
};
完全简单,除了以下行
if (obj.length === +obj.length) results.length = obj.length;
现在,我将其理解为“如果对象长度不是负数......”
如果我的解释是正确的,这意味着它可能是!
那么,亲爱的专家,什么样的对象可能
obj.length === +obj.length
是错误
?我对 ===
的理解意味着如果 obj.length
的类型与 + 的类型不匹配,它可能返回
,但我的知识还不够。 false
obj.length+
可以对 obj.length
可能做的事情做哪些事情? x === +x
是某种我不知道的通用惯用测试吗?它是对 underscore.js 中更深层次出现的某种特殊情况的响应,例如,underscore.js 是否出于某些常规目的分配和跟踪负 object.lengths ?指导和建议将不胜感激。
I was looking at the source code for the Underscore.js library, specifically for the map method (around line 85 on that page, and copied here):
_.map = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
if (obj.length === +obj.length) results.length = obj.length;
return results;
};
completely straightforward EXCEPT for the following line
if (obj.length === +obj.length) results.length = obj.length;
Now, I read this to mean "if the object length is not a negative number..."
which, if my interpretation is right, implies that it might be!
So, dear experts, for what kinds of objects might
obj.length === +obj.length
be false
? My understanding of ===
means it could return false
if the type of obj.length
didn't match the type of +obj.length
, but here my knowledge falls short. What kinds of things could +
do to the kinds of things that obj.length
might be? Is x === +x
some sort of generic idiomatic test that I just don't know? Is it response to some sort of special case that arises deeper in underscore.js, e.g., does underscore.js assign and track negative object.lengths for some conventional purpose? Guidance and advice will be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是测试是否
typeof obj.length === 'number'
而不是它是一个长度值为
'2 days'
的对象所以它知道它是否是一个对象,例如:
vs
I think that's testing to see if
typeof obj.length === 'number'
As opposed to if it's an object that has a length value of
'2 days'
So it knows if it's an object like:
vs
在 javascript 中,
+
运算符还可用于将数字的字符串表示形式转换为数字。因此,这行:也可以表示:“长度是数字而不是字符串”。
In javascript, the
+
operator can also be used to convert a string representation of a number to a number. So the line:can also mean: "length is a number and not a string".