[英]javascript: define a variable if it doesn't exist
我覺得我正在嘗試做一些超級簡單的事情,但只是對此很愚蠢。
我要做的就是查看以前是否設置了變量,如果沒有,則將其設置為默認值....這是一個示例:
if(!embed_BackgroundColor) {
var embed_BackgroundColor;
embed_BackgroundColor = "#F4F4F4";
}
所以,一旦你停止嘲笑我的代碼......為什么無論如何它都會覆蓋變量?
請拯救我的神經;)
專業風格:
var SomeVar = SomeVar || 'Default Value';
if (typeof variable === 'undefined') {
// variable is undefined
// eg:
// var variable = "someValue";
}
在這種情況下,使用三元運算符將是一個很好的編碼實踐。 與 typeof 進行比較時,您也不需要三個等號。 這是最簡潔的解決方案:
b = typeof(b) == 'undefined' ? 0 : b;
這有望節省您的手一些時間。
要真正回答您為什么會發生這種情況的問題 - 它只發生了兩年零一個月多一點:D - 這是因為變量提升。
基本上,在全局范圍內或函數內部執行代碼之前有一個階段,在該階段中掃描所有var
和function
聲明的代碼(不要與函數表達式混淆,但這是另一回事)。
然后所有這些變量和函數都在當前范圍內聲明,只有在此之后代碼才會實際運行。
無論它們在代碼中的位置如何,都會發生這種情況,作用域對應於函數體,而不是語句塊。 是什么讓這更加違反直覺,即使您在聲明中為變量設置了初始值,它們仍將保持“空”狀態,直到在正常執行流程中再次到達聲明。
所以當你寫:
if(!embed_BackgroundColor) {
var embed_BackgroundColor;
embed_BackgroundColor = "#F4F4F4";
}
實際發生的是這樣的:
掃描代碼以查找var
聲明。 embed_BackgroundColor
在此范圍內聲明,無論它是否已經聲明。 它的初始值是未定義的。
代碼開始執行。 運行if
語句。 變量已聲明,但其值未定義,因此條件為真。 使用typeof
不會幫助您區分未聲明的變量和聲明但尚未設置的變量。 反正也沒什么區別。
var
聲明是通過正常的代碼流實現的。 如果你給變量一個初始值,它現在就已經設置好了。 在這種情況下,什么也不會發生。
embed_BackgroundColor
設置為值"#F4F4F4"
。
因此,底線是:您可以使用其他答案中所見的typeof variable == 'undefined'
,甚至可以使用最初使用的普通 '!variable',但不要使用var
否則會破壞一切。
如果它是一個全局變量,我喜歡這樣做:
var defineMe = window.defineMe || 'I will define you now';
使用 window 命名空間很重要,因為引用未定義的變量會導致非常嚴重的錯誤,但引用未定義的屬性不會。
我更喜歡這種語法:
embed_BackgroundColor = embed_BackgroundColor || "#F4F4F4"
沒有比這更簡單的了! 即使它已經變了,它似乎也能工作。
如果 embed_BackgroundColor 是未傳遞的函數中的參數,則可以設置默認值
embed_BackgroundColor ? embedBackgroundColor : embed_BackgroundColor = "#F4F4F4";
全功能示例
function colorFunctionThing(embed_BackgroundColor) {
embed_BackgroundColor ? embed_BackgroundColor : embed_BackgroundColor = "#F4F4F4";
console.log(embed_BackgroundColor);
};
colorFunctionThing();
輸出
#F4F4F4
不完全是你想要的,但仍然很高興知道。
我關注了 Chris West 的博客,看到他在http://gotochriswest.com/blog/2012/07/02/javascript-define-if-undefined/ 上發布了一個非常酷的方式。
基本上,你有define
函數的define
,然后像這樣使用它:
define("embed_BackgroundColor", "#F4F4F4");
如果尚未定義,上面的代碼將在全局上下文中定義 enbed_BackgroundColor。 Chris 使用的示例更有用一點,如下所示:
alert("jStuff is " + (typeof jStuff == "undefined" ? "un" : "") + "defined.");
define("jStuff.alert", function(msg) {
alert(msg);
return msg;
});
alert("jStuff is " + (typeof jStuff == "undefined" ? "un" : "") + "defined.");
var str = jStuff.alert("Show and save this message.");
str
變量中。因為如果embed_BackgroundColor
為false
、 0
、 ""
、 null
、 undefined
或NaN
, if
塊將執行。
但是,如果embed_BackgroundColor
已經分配給另一個非空字符串,則不應覆蓋它......或者至少,它沒有被覆蓋。
正如 Aaron Qian 指出的那樣,也許這是一個范圍沖突的情況。
最佳選擇:
if (typeof someVar === 'undefined') someVar = someValue;
我認為您發布的代碼應該可以工作。 除非你的原始值是 0。
問題出在其他地方。
我猜你在代碼范圍之外定義了 'embed_BackgroundColor'。 當您運行您的代碼時,該變量在您的代碼范圍內未定義,並將被分配默認值。
下面是一個例子:
var embed_BackgroundColor = "#FF0000";
(function(){
if(!embed_BackgroundColor) {
var embed_BackgroundColor;
embed_BackgroundColor = "#F4F4F4";
}
alert(embed_BackgroundColor); // will give you #F4F4F4
})();
alert(embed_BackgroundColor); // will give you #FF0000;
我更喜歡類似 PHP 風格的通用解決方案:
function isset(x) { return typeof(x)!='undefined'; }
從 ES2020 開始,您現在可以使用無效合並運算符??
. 這避免了將虛假值重新分配給默認值。
var embed_BackgroundColor = embed_BackgroundColor?? "#F4F4F4"
請注意,如果您正在執行這樣的 oneliner,則需要使用var
; let
和const
不會讓你在一行中完成。
2022 ECMA 語法中最簡潔的方法!!
如果您想覆蓋“nullish”值(請參見下面的參考文獻),請使用let might_exist ||= default
分配或使用(might_exist || default)
傳遞值。 (括號只是為了清楚起見並避免運算符優先級問題,如果您願意,請刪除。)
如果您想保留“nullish”值,請使用let might_exist??= default
分配或使用(might_exist?? default)
傳遞值。
關於無效: ??
只會覆蓋null
和undefined
,而||
還將覆蓋“nullish”值,例如''
和0
。
不客氣,我是時候回饋一律了
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment
if(embed_BackgroundColor == "" || embed_BackgroundColor == 'undefined' || embed_BackgroundColor == null){
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.