Javascript:两个if类型的未定义语句,给出不同的结果

Javascript:两个if类型的未定义语句,给出不同的结果,javascript,jquery,html,typeof,playframework-2.3,Javascript,Jquery,Html,Typeof,Playframework 2.3,运行play framework 2.3版,但可能与此无关: 我有一个包含以下内容的html文件: <html> <head> <script type="text/javascript"> if (typeof x === 'undefined') {console.log("x not defined");} else {console.log("in html, x is %s", typeof x);} </script&

运行play framework 2.3版,但可能与此无关:

我有一个包含以下内容的html文件:

<html>
    <head>
        <script type="text/javascript"> if (typeof x === 'undefined') {console.log("x not defined");} else {console.log("in html, x is %s", typeof x);} </script>
        <script type="text/javascript" src="javascripts/somescript.js"></script>
    </head>
</html>
当我第一次加载页面时,x未按预期定义。但是,当我转到同一应用程序中的不同页面,然后返回时,控制台显示:

in html, x is object
in somescript.js, x is undefined
这很奇怪,因为在html中,if语句为false,但在somescript.js中,if语句为true也是如此


为什么要这样做?我如何确保两个脚本以相同的方式运行?

这是变量提升-如果在函数中的任何位置声明变量,它的定义将被提升到顶部

x = 0;
function y() {
    //var x; you don't write it here, but internally this is happening
    if (typeof x === 'undefined') {
        alert('x is undefined');
        var x = 1; //because you use var, you are declaring a new variable x,
                   //so it gets hoisted to the top
    }
}
y(); //alerts x is undefined
但如果你这样做了:

x = 0;
function y() {
    if (typeof x === 'undefined') {
        alert('x is undefined');
        x = 1; //we don't use var, so we aren't redeclaring it, just setting its value
    }
}
y(); //nothing happens

每个都在测试不同范围内的不同
x
变量。请注意,somescript.js中
var x
的声明位于
函数的顶部,位于
if
上方。而且,这里可能没有显示的其他内容是定义一个全局
x
@JonathanLonowski好的捕获。在somescript.js的
if
x
总是未定义的,因为它的声明被提升,全局
x
可能重复。也相关
x = 0;
function y() {
    if (typeof x === 'undefined') {
        alert('x is undefined');
        x = 1; //we don't use var, so we aren't redeclaring it, just setting its value
    }
}
y(); //nothing happens