js中三元等于比较和数组长度
最后,我浏览了 Underscore.js 代码来学习 JavaScript 习惯用法,我发现了以下内容each
函数的定义:
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
这一行的用途是什么? (我认为这是一种检查传递的对象是否是数组的方法,对吗?如果是这样,那么 typeof
运算符不是更好的方法吗?)
obj.length === +obj.length
Lastly I was skimming through Underscore.js code to learn JavaScript idioms and I found following definition of each
function:
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
What this line is for? (I assume that this is a way of checking if passed object is an array, am I right? If so, wouldn't be an typeof
operator better approach?)
obj.length === +obj.length
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
each
方法接受集合(数组或对象)。在检查本机方法 forEach 是否可用后,该方法检查 obj 是否是一个数组。使用
typeof
是不可能的,因为 typeof 将为数组和对象返回"object"
(尝试typeof [] === typeof {}
)。因此,他们使用了 obj.length === +obj.length 方法。这是有效的,因为如果
obj
没有length
属性,+obj.length
返回NaN
并且严格比较失败。然后,该方法假设 obj 是一个对象。The
each
method accepts Collections (Arrays or Objects).After checking if the native method forEach is available, the method checks if
obj
is an Array. This is not possible usingtypeof
since typeof will return"object"
for arrays as well for objects (trytypeof [] === typeof {}
). So, they used theobj.length === +obj.length
approach.This works because if
obj
doesn't have thelength
property,+obj.length
returnsNaN
and the strict comparison fails. Then, the method assumesobj
is anobject
.+obj.length 将返回一个数值。 === 比较对象的类型及其值。换句话说,它执行严格的比较。
http://geekswithblogs .net/brians/archive/2010/07/03/quality-equality-with-javascript-quotquot-gt-quotquot.aspx
+obj.length will return a numerical value. === compares the type of the objects and their values. In other words it performs a strict comparison.
http://geekswithblogs.net/brians/archive/2010/07/03/quality-equality-with-javascript-quotquot-gt-quotquot.aspx
这一行:
是必要的,因为
会返回
this line:
is necessary because
will return