Underscore.js 中的加号运算符是什么意思? [英] What does plus operator mean in Underscore.js?
问题描述
当我看到 Underscore.js(1.4.3 版)代码时,我看到了以下几行(79 行)
While I was seeing Underscore.js (version 1.4.3) code, I saw following lines (79 line)
if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
}
我不明白为什么在 if 语句中使用 +
运算符.(+obj.length)
而且,这句话不总是真实吗?
我不认为这是一个错字.必须有一些目标才能使用它.如果有人知道这种用法的好处,我想在将来使用它.
谢谢.
I didn't understand why +
operator used within if statement. (+obj.length)
And, isn't it this statement always true?
I don't think it's a typo. There must be some aim to use that. If anyone knows benefits of this usage, I want to use it in future.
Thanks.
推荐答案
obj.length
可以是任何类型 - 例如 undefined
.+obj.length
总是一个数字.
obj.length
might be any type - such as undefined
. +obj.length
is always a number.
所以代码基本上会检查 length
属性是否存在并且是一个数字.这个检查的原因是 _.each()
接受数组和非数组对象.在数组的情况下,length
属性是迭代其元素所必需的,而 for..in
循环是非数组对象的方法.
So the code basically checks if the length
property exists and is a number. The reason for this check is that _.each()
accepts both arrays and non-array objects. In case of an array the length
property is necessary to iterate over its elements while a for..in
loop is the way to go in case of a non-array object.
这篇关于Underscore.js 中的加号运算符是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!