array.length与array.length> 0

[英]array.length vs. array.length > 0


Is there any difference between checking an array's length as a truthy value vs checking that it's > 0?

将数组的长度检查为真值并检查它是否> 0之间有什么区别吗?

In other words is there any reason to use one of these statements over the other:

换句话说,有没有理由使用其中一个语句而不是另一个:

var arr = [1,2,3];
if (arr.length) {
}

if (arr.length > 0) {
}

3 个解决方案

#1


3  

array.length is fastest and shortest than array.length > 0. You can see difference of their speeds : http://jsperf.com/test-of-array-length

array.length比array.length> 0最快和最短。你可以看到它们的速度差异:http://jsperf.com/test-of-array-length

if(array.length){...} is similar to if(0){...} or if(false){...}

if(array.length){...}类似于if(0){...}或if(false){...}

#2


9  

Is there any difference between checking an array's length as a truthy value vs checking that it's > 0?

将数组的长度检查为真值并检查它是否> 0之间有什么区别吗?

Since the value of arr.length can only be 0 or larger and since 0 is the only number that evaluates to false, there is no difference.

由于arr.length的值只能是0或更大,因为0是唯一的计算结果为false的数字,所以没有区别。

In general, Boolean(n) and Boolean(n > 0) yield different results for n < 0.

通常,布尔(n)和布尔(n> 0)对n <0产生不同的结果。

In other words is there any reason to use one of these statements over the other

换句话说,是否有任何理由将这些陈述中的一个用于另一个陈述

Only reasons related to code readability and understanding, not behavior.

只有与代码可读性和理解相关的原因,而不是行为。

#3


5  

In javascript, they dont make a difference.

在javascript中,它们没有任何区别。

In the end, whatever is in between the if parenthesis will evaluate to a truthy or falsey value

最后,if括号之间的任何内容都将评估为真值或假值

For all possible falsey values, see All falsey values in JavaScript

对于所有可能的falsey值,请参阅JavaScript中的所有falsey值

If you wish to be more clear and explicit, use

如果您希望更清晰明确,请使用

if (arr.length > 0) {
}

If you wish to be less verbose, use

如果你想减少冗长,请使用

if (arr.length) {
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2015/10/02/2617a27428fc4ca9c713d4e9f0e67f55.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号