我認爲下面會的工作,x
是否申報或賦值或不:如果(x)的...給出了參考錯誤:X沒有定義
if (x)
console.log("x is well defined");
else
console.log("x is not defined or null or false or 0 ...");
但是,我得到(當x
無法在我的代碼中聲明):
x is not defined
爲什麼會發生這種情況?
(這是在Node.js的環境。)
我認爲下面會的工作,x
是否申報或賦值或不:如果(x)的...給出了參考錯誤:X沒有定義
if (x)
console.log("x is well defined");
else
console.log("x is not defined or null or false or 0 ...");
但是,我得到(當x
無法在我的代碼中聲明):
x is not defined
爲什麼會發生這種情況?
(這是在Node.js的環境。)
,如果你不在,如果範圍的任何地方x聲明(x)語句,會有參考錯誤。
爲了避免這種情況,只需聲明var x;在if(x)語句或其父範圍的範圍內。
現在,如果您只是聲明:
var x;
這裏x的值是未定義的,所以其他部分將被執行。
但是,如果你定義爲:
var x = 1;
然後if語句將真實輸出是x被很好地定義
這裏的jsfiddle:https://jsfiddle.net/raushankumar0717/4ozmf7r5/
var x=1;
if(x)
\t alert("Defined");
else
alert("Not Defined");
謝謝大家的回答。我和Jade(aka Pug)中的Javascript混淆了。在Jade中,總是可以測試一個未聲明的變量。 Jade仍然是Javascript,但顯然未聲明的變量在進入Jade腳本時被賦予默認值。 –
按我的知識...... 如果我們看到x的值是「不確定」,因此它會給一個TypeError!
If u see this..
if(typeof x === 'undefined')
console.log("x is well defined");
這會給輸出「x被明確定義」 糾正我,如果我有從你的問題別的東西! :)
當if(x)
時跑時,x
檢查並沒有定義,所以你的if/else意味着什麼時,JavaScript遇到未捕獲錯誤。
你可以把它放在try/catch中,它會捕獲錯誤,但是你的if/else不會記錄任何東西。相反,你需要做的是這樣的:
if (typeof x !== 'undefined')
console.log("x is well defined");
else
console.log("x is not defined or null or false or 0 ...");
或者,如果你還需要檢查「x」是truthy,你可以使用:
if (typeof x !== 'undefined' && x)
console.log("x is well defined");
else
console.log("x is not defined or null or false or 0 ...");
如果x沒有聲明這將這樣做(這是一個預期的行爲),另一方面'typeof x!=「undefined」不會拋出任何錯誤,即使x沒有被聲明。 – Vivick
即使使用'typeof',你也可以得到參考錯誤,如果你真的依靠靜態分析,它會更好。 – MinusFour
你想知道什麼?你似乎已經知道了解決方案:當你想使用它時,在代碼中聲明'x'。 – Bergi