What does plus operator mean in Underscore.js?

妖精的绣舞 提交于 2019-12-22 01:02:31

问题


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;
        }
    }

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.


回答1:


obj.length might be any type - such as undefined. +obj.length is always a number.

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.




回答2:


The plus operator converts a value to Number.

Basically, a === +a makes sure a is a number and not a string.




回答3:


It converts a value to a number. I found this article helpful:

http://www.2ality.com/2012/01/object-plus-object.html

Cheers! :)




回答4:


The unary + operator results in the numeric equivalent of its operand, and NaN if the operand cannot be converted to a number.

It's one of a number of little "tricks" that exist in Javascript:

  • !!foo - converts foo to a boolean
  • ~~foo - converts foo to a 32-bit signed integer


来源:https://stackoverflow.com/questions/15270843/what-does-plus-operator-mean-in-underscore-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!