【问题标题】:How to check if a variable exist in jquery如何检查jquery中是否存在变量
【发布时间】:2012-07-05 18:36:57
【问题描述】:

我在 jquery 代码中有两个变量,如果 item.a 不存在,它会输出一个“null”,所以我想检查变量是否存在。代码如下:

.append( "<a>" + item.a + ", " + item.b + "</a>" )

如果没有“item.a”,则会导致

null, Blabla

我试过这个 if / else 语句,但它什么也没返回

.append( "<a>" + (item.a) ? item.a : + ", " + item.b + "</a>" )

有什么想法吗?

【问题讨论】:

标签: jquery


【解决方案1】:

您的尝试很接近。试试这个:

.append( "<a>" + (item.a ? item.a : "") + ", " + item.b + "</a>" )

或者,假设您在没有item.a 时不想要逗号:

.append( "<a>" + (item.a ? item.a + ", " : "") + item.b + "</a>" )

【讨论】:

  • @Alnitak - 是的,可能。我已经添加进去了。
【解决方案2】:

你使用的条件运算符

编辑

.append( "<a>" + (item.a != null ? item.a + ", " : "") + item.b + "</a>" )

如果变量为空

if(varName === null)
{
    alert("variable has null");
}

如果变量不存在

if(typeof varName === 'undefined')
{
    alert("variable not defined");
}

【讨论】:

猜你喜欢
  • 2014-01-30
  • 2010-10-25
  • 2011-08-18
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 2015-12-01
  • 2014-09-08
相关资源
最近更新 更多