What does a + prefix do in this context?

后端 未结 5 581
栀梦
栀梦 2021-01-27 04:23

Here is a line of code from underscore. What is that plus prefix for in this line?

if (obj.length === +obj.length) { // plus prefix?
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-27 04:43

    If the object does not have a length property (being a regular Object, instead of an Array), then calling obj.length will return undefined. A test for undefined would be clearer, but the implementor chose to first convert it to a number (so it will become NaN) and then compare it with the original value (using a strict comparison, which will ensure it will yield false).

    Update: as others pointed out, this code seems to be concerned not only with Arrays, but also "array-like" objects (i.e. objects that have a numeric length property and numeric indices). In such case, a test for instanceof Array would not be enough (and just testing for undefined might not be the best option, since there could be a length but of another type).

提交回复
热议问题