JavaScript isset()函数

dhi*_*hiv 7 javascript php

如何检查issetjavascript.

我用以下方式.

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*oki 15

你可以这样做:

if(sessionvalue)
Run Code Online (Sandbox Code Playgroud)

上面的代码将自动检查undefined,null(而且NaN,false,"")

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

function isset(_var){
     return !!_var; // converting to boolean.
}
Run Code Online (Sandbox Code Playgroud)


AyB*_*AyB 13

当未声明javascript变量并且您尝试调用它们时,它们将返回undefined,因此您可以执行以下操作:

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