Javascript if (var.length >0){} 和 if (var){} 之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6393831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between if (var.length >0){} and if (var){}
提问by mazlix
In javascript is there a difference between using
在javascript中使用
if (foo.length > 0) {
//run code involving foo
}
and
和
if (foo) {
//run code involving foo
}
If so, could someone please explain the difference and an example where they would not be the same?
如果是这样,有人可以解释它们之间的差异和一个例子吗?
回答by Mark Eirich
Here's an example where they are not the same:
这是一个示例,其中它们不相同:
var x = [];
alert(x? 'yes' : 'no'); // displays "yes"
alert((x.length > 0)? 'yes' : 'no'); // displays "no"
回答by James Montagne
The two are completely different. I'm assuming by the use of .length
that var
is a jquery object, in which case if(var)
will always be true. jQuery will always return an object, but it may be empty. if(var.length>0)
checks that the jquery object actually contains an element.
两者完全不同。我假设使用.length
它var
是一个 jquery 对象,在这种情况下if(var)
将始终为真。jQuery 将始终返回一个对象,但它可能为空。 if(var.length>0)
检查 jquery 对象是否实际包含一个元素。
回答by Flimzy
The former tests if var.length returns more than 0. The latter tests if the value of var is true.
前者测试 var.length 的返回值是否大于 0。后者测试 var 的值是否为真。
You cannot necessarily use either one for all variables. For a boolean, if(var) makes more sense. For a string or array, if(var.length) makes more sense.
您不一定对所有变量都使用其中之一。对于布尔值, if(var) 更有意义。对于字符串或数组, if(var.length) 更有意义。
回答by nathan gonzalez
they're obviously different, the question is really just why are they different.
他们显然不同,问题是他们为什么不同。
your first example is explictly checking that the length property of an object is greater than 0. if that is true it evaluates the content of the if statement.
您的第一个示例是明确检查对象的长度属性是否大于 0。如果为真,则评估 if 语句的内容。
the second example can only tell you if the variable is 'truthy', or 'falsy' (or as the great stephen colbert coined it, 'truthiness'). check out the wikipedia article on javascript booleansfor detail.
第二个例子只能告诉你变量是“真实”还是“虚假”(或者像伟大的斯蒂芬科尔伯特创造的那样,“真实”)。有关详细信息,请查看有关 javascript 布尔值的维基百科文章。