[英]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.