jQuery 变量是否未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1485840/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:34:42  来源:igfitidea点击:

Whether a variable is undefined

jquery

提问by Phil Hymanson

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; }

回答by ScottyUCSD

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:

jQuery.val() 和 .text() 永远不会为空选择返回 'undefined'。它总是返回一个空字符串(即“”)。如果元素不存在,.html() 将返回 null。您需要执行以下操作:

if(page_name != '')

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

对于不是来自 jQuery.val() 之类的其他变量,您可以这样做:

if(typeof page_name != 'undefined')

You just have to use the typeofoperator.

你只需要使用typeof运算符。

回答by Roger

if (var === undefined)

if (var === undefined)

or more precisely

或更准确地说

if (typeof var === 'undefined')

if (typeof var === 'undefined')

Note the ===is used

注意===是使用

回答by Roger

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.)

这避免使用typeof whatever === "undefined". (此外,没有任何字符串连接。)

回答by micmcg

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

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; }

回答by Rich Seller

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

您可以直接检查变量。如果未定义,它将返回一个值。

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; }