[英]why does a variable in javascript seem to hold the value “undefined” even when it was defined
如果我運行以下javascript代碼,瀏覽器將發出“ undefinedabc”警報。
var x;
x += "abc";
alert(x);
在我看來,我確實定義了變量x,那么為什么它似乎未定義?
var x = "";
x += "abc";
alert(x);
嘗試這個。 您正在嘗試添加'abc'
和undefined
,這將導致undefinedabc
。
undefined
是未分配任何值的任何變量的默認值。 因此, var x;
表示a = undefined
。 當您添加"abc"
時,實際上是在執行undefined + "abc"
。 最后,將undefined
字符串化為"undefined"
,然后將其串聯為"abc"
然后變為"undefinedabc"
。
為了對var x
進行初始化,您應該為其分配一個空字符串(請記住JavaScript是二維類型的):
var x = '';
x += "abc";
alert(x); // "abc"
此MDN文章介紹了此行為。
首先檢查變量語句的行為,特別是:
"Variables are initialised to undefined when created."
然后檢查加法運算符的行為( 復合賦值應用該運算符的行為對應於=
之前的行為)。
具體來說,要點7:
"If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)"
因此,根據ToString的說法,由於"abc"
是字符串,因此x
將被轉換為字符串。 從上面我們知道,x是不確定的。
最后,檢查抽象操作ToString的行為,特別是未定義的參數導致字符串“ undefined”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.