Javascript 如何使用javascript检查var是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5519732/
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
how to check if var is not empty with javascript?
提问by Mike
Not having much luck with this. I'm trying to determine if a var is not empty.
没有太多运气。我正在尝试确定 var 是否不为空。
$('#content').mouseup(function() {
var selection = getSelected();
if (typeof(selection) !=='undefined') {
alert(selection);
}
});
What this is doing is grabbing any text the user has selected -- but it shows an empty alert even if the user just mouseup's on the div.
这样做是抓取用户选择的任何文本——但它显示一个空警报,即使用户只是在 div 上使用鼠标。
采纳答案by Guffa
Your code is perfectly accurate for detecting an undefined value, which means that the function always returns some kind of value even if there is no selection.
您的代码对于检测未定义的值非常准确,这意味着即使没有选择,该函数也始终返回某种值。
If the function for example returns a selection object (like the window.getSelection
function), you check the isCollapsed
property to see if the selection is empty:
例如,如果函数返回一个选择对象(如window.getSelection
函数),则检查该isCollapsed
属性以查看选择是否为空:
if (!selection.isCollapsed) ...
回答by Jamie Treworgy
Just say:
说啊:
if (selection) {
alert(selection);
}
The simple true/false test in Javascript returns true if the member is defined, non-null, non-false, non-empty string, or non-zero.
如果成员已定义、非空、非假、非空字符串或非零,Javascript 中的简单真/假测试将返回真。
Also, in Javascript, something can be equal to a value undefined
or actually undefined (meaning, no such named object exists). e.g.
此外,在 Javascript 中,某些东西可以等于一个值undefined
或实际上未定义(意思是,不存在这样的命名对象)。例如
var x = undefined;
alert(x===undefined); /* true; */
alert(x); /* false */
x=1;
alert(x); /* true */
alert(y===undefined); /* reference error - there's nothing called y */
alert(y); /* reference error */
alert(typeof y === "undefined"); /* true */
As the comment below notes, if you are not sure if something even exists at all, you should test that first using typeof
.
正如下面的评论所指出的,如果您不确定某些东西是否存在,您应该首先使用typeof
.
回答by danniel
you can simply use:
你可以简单地使用:
if (selection) {
alert(selection);
}