变量是否未定义 [英] Whether a variable is undefined

查看:83
本文介绍了变量是否未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
检查JavaScript中未定义"的最佳方法?

Possible Duplicate:
Best way to check for "undefined" in JavaScript?

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

How do I find if a variable is undefined?

我目前有:

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()和.text()永远不会为空选择返回'undefined'.它总是返回一个空字符串(即").如果元素不存在,则.html()将返回null.您需要这样做:

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 != '')

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

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

if(typeof page_name != 'undefined')

您只需要使用typeof运算符.

You just have to use the typeof operator.

这篇关于变量是否未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆