最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Could array.length be below 0 in Javascript? - Stack Overflow

programmeradmin1浏览0评论

Since people are often using

array.length < 1

to check if an array is empty instead of

array.length === 0

I wonder if there are cases array.length could be below 0.

Since people are often using

array.length < 1

to check if an array is empty instead of

array.length === 0

I wonder if there are cases array.length could be below 0.

Share Improve this question asked Nov 19, 2011 at 0:08 ajsieajsie 79.7k110 gold badges284 silver badges386 bronze badges 2
  • 2 Your question is incomplete. Don't forget about rulling out fractional lengths, like 0.5 ;) – hugomg Commented Nov 19, 2011 at 0:14
  • @missingno: I went ahead and answered that part, too. ;-) – T.J. Crowder Commented Nov 19, 2011 at 0:22
Add a comment  | 

1 Answer 1

Reset to default 23

No, the length of an array is a non-negative integer. From the spec:

Every Array has a non-configurable "length" property whose value is always a non-negative integral Number whose mathematical value is less than 2^32.

(my emphasis)

So either check is perfectly fine, and both will have the same result for all arrays.

You may find people arguing for === 0 over < 1 on the grounds of performance, because the IsStrictlyEqual algorithm would take fewer steps than the IsLessThan algorithm. Granted that's true, but I'm aware of no evidence that either is faster than the other in this use-case (and I've tested it; sadly the jsPerf test is gone now). (Or others may argue that < will do type conversion and === won't, but that's irrelevant here; both types are the same.) But even if it were that one was minutely faster than the other, you'd have to be doing the comparison literally billions of times to see even the smallest real-world impact.

发布评论

评论列表(0)

  1. 暂无评论