为什么不警告以下行?
<script>
alert(x);//this line is not executed or alerted ???.It should have alerted "undefined"
console.log(x)//reference error
var y="maizere";
alert(y);//this line is also not executed or alerted ???
</script>
任何未声明的变量在javascript中被视为全局变量吗?
答案 0 :(得分:2)
alert(x);//this line is not executed or alerted ???.It should have alerted "undefined"
那是不对的。此行引发ReferenceError
,因为没有变量x
。
将此情况与情况进行对比:
var obj = {};
alert(obj.x); // undefined - there's no attribute x
答案 1 :(得分:2)
您的undefined
和undeclared
混淆了。
变量x
未声明 - 尚未在代码中声明,所以
alert(x);
会引发'x' is not declared
之类的错误。
您的代码应该是
<script>
var x;
alert(x);//this line is not executed or alerted ???.It should have alerted "undefined"
var y="maizere";
alert(y);//this line is also not executed or alerted ???
</script>
答案 2 :(得分:0)
应该定义您在alert
电话中放置的内容。如果不是(您的情况)则会抛出错误。因此,您应该首先定义变量。对于错误,您应该检查JavaScript(浏览器)控制台。
var x = "Test";
alert(x); // shows
var y = 123;
alert(y); // y also shows, because there is no error thrown inside the alert for x