【问题标题】:JavaScript isset() function [duplicate]JavaScript isset()函数[重复]
【发布时间】:2014-06-09 08:50:00
【问题描述】:

如何在javascript中检查isset

我用过如下方式。

var sessionvalue = document.getElementById('sessionvalue').value;

if(Here I have to check if isset the sessionvalue or not){

  if(sessionvalue == "" || sessionvalue == null)
    {
        document.getElementById('sessionvalue').style.borderColor="red";
        return false;
    }
    else
    {
        document.getElementById('sessionvalue').style.borderColor="#ccc";
    }
}

【问题讨论】:

  • 类似但不是重复的问题.. 家伙在问一个变量,引用的问题是在问数组值。这是个好问题。

标签: javascript php


【解决方案1】:

你可以这样做:

if(sessionvalue)

上面会自动检查undefinednull(和NaNfalse""

如果你需要它,你甚至可以让它成为一个全局函数,就像你在 php 中习惯的那样。

function isset(_var){
     return !!_var; // converting to boolean.
}

【讨论】:

  • 太棒了,谢谢!还可以检查多个变量,例如 if ( (var1) && (var2) ) {}
【解决方案2】:
    if(typeof(data.length) != 'undefined')
    {
       // do something
    }

    if(empty(data))
    {
        // do something
    }

   if(typeof(data) == 'undefined' || data === null)
   {
     //do something
   }

【讨论】:

    【解决方案3】:

    试试下面的代码

    var sessionvalue=document.getElementById('sessionvalue').value;
    if(typeof sessionvalue != 'undefined'){
    
        if(sessionvalue=="" || sessionvalue == null)
        {
            document.getElementById('sessionvalue').style.borderColor="red";
            return false;
        }
        else
        {
            document.getElementById('sessionvalue').style.borderColor="#ccc";
    
    
        }
    }
    

    【讨论】:

      【解决方案4】:

      你可以只做if(sessionvalue) 就可以了将是:

      document.getElementById('sessionvalue').style.borderColor= sessionvalue ? "red" : "#CCC";
      

      【讨论】:

        【解决方案5】:

        当 javascript 变量未声明并且您尝试调用它们时,它们会返回 undefined,因此您可以这样做:

        if (typeof sessionvalue == "undefined" || sessionvalue == null)

        【讨论】:

        • 然而if (typeof(sessionvalue.property) == "undefined" || sessionvalue.property == null) 会导致Uncaught ReferenceError: sessionvalue is not defined 异常,所以在实现更接近isset 的东西时,这只是冰山一角。相应地投反对票。
        • @user3338098 问题是关于对象是否存在而不是对象的属性。很明显,为了使对象的属性存在,对象必须首先存在。所以在这里你的情况会略有变化。您将首先检查对象是否存在,如果存在,则继续寻找该属性。请参考此处的示例:jsfiddle.net/kx6gcLLm
        • 无论哪种方式,等同于检查任意数量属性的 php isset 函数在本质上是完全不同的。考虑: php: isset(a->b->c->d->e->f) 和现在 javascript if (typeof a == "undefined" || a == null || typeof(a.b) == "undefined" || a.b == null || typeof(a.b.c) == "undefined" || a.b.c == null || typeof(a.b.c.d) == "undefined" || a.b.c.d == null || typeof(a.b.c.e) == "undefined" || a.b.c.e == null || typeof(a.b.c.e.f) == "undefined" || a.b.c.e.f == null) 现在我们可以看到差异如此极端以至于毫无用处。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-18
        • 2010-10-10
        • 2012-08-23
        • 2021-03-25
        • 2017-08-02
        • 1970-01-01
        相关资源
        最近更新 更多