how to check if var is not empty with javascript?
Not having much luck with this.开发者_如何学C I'm trying to determine if a var is not empty.
$('#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.
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.
Also, in Javascript, something can be equal to a value undefined
or actually undefined (meaning, no such named object exists). e.g.
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
.
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:
if (!selection.isCollapsed) ...
you can simply use:
if (selection) {
alert(selection);
}
精彩评论