Whether a variable is undefined
Possible Duplicate:
Best way to check for “undefined” in JavaScript?
How do I find if a variable is undefined?
I currently have:
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; }
jQuery.val() and .text() will never return 'undefined' for an empty selection. It always returns an empty string (ie ""). .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.
if (var === undefined)
or more precisely
if (typeof var === 'undefined')
Note the ===
is used
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.)
上一篇: 将现有的git存储库推送到SVN
下一篇: 一个变量是否是未定义的