[英]Check if variable is (defined) not working in JavaScript
被這種行為弄糊塗了。 我想這樣做:
if (variable name)
{
... do this...
}
應該管用。 但是,如果未定義變量,我只會得到“ReferenceError:找不到變量:”變量名,並且 else 塊甚至不會被執行。例如,我從另一個 StackOverflow 問題中得到的以下代碼片段沒有當我測試它時工作。有什么建議嗎?
if(persons_name)
{
var name = persons_name;
}
else
{
var name = "John Doe";
}
if (typeof persons_name !== 'undefined') {
...
} else {
...
}
請注意,您不需要帶有typeof
的大括號。
與屬性不同,必須先定義非限定名稱,然后才能使用它。 所以如果你正在尋找一個全局變量persons_name,你可以寫
if (window.persons_name)
如果 person_name 不存在,它將評估為未定義。 或者,如果您希望它存在,您可以簡單地聲明persons_name。
var persons_name;
如果 person_name 已經存在,這不會改變它的值。
通過說var name;
你定義變量; 並通過說var name = "john doe";
你給它一個值。
var name = (typeof persons_name !== 'undefined' || !(!!persons_name)) ?
persons_name :
'John Doe';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.