2014-04-24 112 views
5

如何在javascript中檢查issetJavaScript 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"; 
    } 
} 

回答

8

當JavaScript變數聲明,試圖給他們打電話,他們返回undefined,所以你可以做:

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

+1

,但如果' (typeof(sessionvalue.property)==「undefined」|| sessionvalue.property == null)'導致了異常'Uncaught ReferenceError:sessionvalue沒有被定義',所以只有冰山的一角才能實現甚至接近'isset'的東西。相應地投票。 – user3338098

+0

@ user3338098問題是關於對象是否存在,而不是對象的屬性。很明顯,爲了使對象的屬性存在,對象必須首先存在。所以在這裏你的情況會稍微改變。你會檢查對象是否先存在,如果存在,繼續尋找屬性。請參閱此處的示例:https://jsfiddle.net/kx6gcLLm/ –

+0

無論如何,它與* php *'isset'函數等效,它檢查任意數量的屬性,本質上是完全不同的。考慮:php:'isset(a-> b-> c-> d-> e-> f)'現在* javascript *'if(typeof a ==「undefined」|| a == null || typeof ab)==「undefined」|| ab == null || typeof(abc)==「undefined」|| abc == null || typeof(abcd)==「undefined」|| abcd == null || typeof (abce)==「undefined」|| abce == null || typeof(abcef)==「undefined」|| abcef == null)'現在我們可以看到差異如何極端以至於無用。 – user3338098

11

你可以這樣做:

if(sessionvalue) 

以上將自動檢查undefined,null(和NaN,false,""

你甚至可以使它成爲一個全局函數,如果你需要它,就像你習慣於在PHP中。

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

你可以做if(sessionvalue)就是這樣,你不需要任何東西,記住,你可以在JavaScript中的汽車比較蘋果,你可以檢查,如果值爲null或undefined與if(sessionvalue)if(!sessionvalue),你的代碼會:

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

try代碼如下

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


    } 
} 
0
if(typeof(data.length) != 'undefined') 
    { 
     // do something 
    } 

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

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