变量是否未定义

如何查找变量是否未定义?

我目前有:

var page_name = $("#pageToEdit :selected").text();
var table_name = $("#pageToEdit :selected").val();
var optionResult = $("#pageToEditOptions :selected").val();


var string = "?z=z";
if ( page_name != 'undefined' ) { string += "&page_name=" + page_name; }
if ( table_name != 'undefined' ) { string += "&table_name=" + table_name; }
if ( optionResult != 'undefined' ) { string += "&optionResult=" + optionResult; }
459436 次浏览

You can just check the variable directly. If not defined it will return a falsy value.

var string = "?z=z";
if (page_name) { string += "&page_name=" + page_name; }
if (table_name) { string += "&table_name=" + table_name; }
if (optionResult) { string += "&optionResult=" + optionResult; }

jQuery.val() and .text() will never return 'undefined' for an empty selection. It always returns an empty string (i.e. ""). .html() will return null if the element doesn't exist though.You need to do:

if(page_name != '')

For other variables that don't come from something like jQuery.val() you would do this though:

if(typeof page_name != 'undefined')

You just have to use the typeof operator.

http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html

Depends on how specific you want the test to be. You could maybe get away with

if(page_name){ string += "&page_name=" + page_name; }
function my_url (base, opt)
{
var retval = ["" + base];
retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
return retval.join("");
}


my_url("?z=z",  { page_name : "pageX" /* no table_name and optionResult */ } );


/* Returns:
?z=z&page_name=pageX
*/

This avoids using typeof whatever === "undefined". (Also, there isn't any string concatenation.)

if (myVariable === undefined)

or more precisely

if (typeof myVariable === 'undefined')

Note the === is used