2017-06-04 44 views
-3

在Javascript中我能做到這一點...的Javascript校驗值不存在

myvalue = "greenapples" 

if (myvalue) { 
    alert ("My Value is " + myvalue) 
} 

可是我該怎麼做相反?如果未設置myvalue,我想顯示警報。

任何人都有我能看到的例子嗎?

+1

使用'!myvalue'。或者更好'if(myvalue == undefined)' – Satpal

+0

另外,不要在沒有聲明關鍵字的情況下創建變量。 – thefourtheye

回答

0

typeof myvalue === 'undefined'!myvalue是檢查變量是否存在的兩種方法。

if (typeof myvalue === 'undefined') { 
    alert ("variable does not exist"); 
} 

if (!myvalue) { 
    alert ("variable does not exist"); 
} 
+0

與第二,第一是不必要的 –

+0

是的,你是對的。我編輯了我的答案。 – WizardCoder

0

您可以通過兩種方式來實現:

一個是你可以簡單地使用(不)操作:

VAR myvalue的= 「greenapples」;

if (!myvalue) { 
    alert ("My Value not set"); 
} 

OR

您也是一個else語句可以:

var myvalue = "greenapples"; 

if (myvalue) { 
    } 
else{ 
    alert ("My Value not set "); 
} 

這是說,如果一個變量的值是不確定的,那麼別的什麼也不做提醒用戶。或者如果你想要在第一個代碼的上下文中,它說如果變量的值不是未定義的,那麼執行程序

使用!(not)運算符只是在程序中節省了一點控制權。所以,你很可能會使用!(不)運算符

1

1的方式..

var myvalue = "greenapples"; 

if (myvalue === undefined){ 
alert("My Value Is "+ myvalue) 
} 

第二路

var myvalue = "greenapples"; 

    if (!myvalue) { 
     alert("My Value is" + myvalue); // Javascript executes this row 
    } else { 
     alert("This Is Already Set"); 
    } 

3路

typeof運營商將檢查變量確實是不確定的。

var myvalue = "greenapples"; 
if (typeof myvalue === 'undefined' || myvalue=== null) { 
    // variable is undefined and null then 
    alert("My Value Is "+ myvalue); 
}