Javascript:两个if类型的未定义语句给出不同的结果
Javascript: two if typeof undefined statements giving different results
运行游戏框架版本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>
和somescript.js有这个:
(function() {
jQuery(function() {
if (typeof x === 'undefined') {
console.log("in somescript.js, x is %s", typeof x);
var x = something;
//other stuff
}
});
}).call(this);
当我第一次加载页面时,x是未定义的。但是,当我转到同一应用程序中的不同页面,然后返回时,控制台读取:
in html, x is object
in somescript.js, x is undefined
这很奇怪,因为在html中,if语句为假,但在somescript.js中,相同的if语句为真。
为什么要这样做,我如何确保两个脚本以相同的方式运行?
这是变量提升——如果你在函数内部的任何地方声明一个变量,它的定义将被提升到顶部。
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
相关文章:
- 如何知道javascript for语句中的所有结果是否都是错误的
- If语句只执行第一个条件并运行其他条件,但没有结果
- 嵌套在WHILE循环中的IF语句的结果混淆了我(Javascript)
- 如何在js中等待if语句内部的结果
- 为什么我的JS"如果“;语句的求值结果总是为false
- IF 语句不改变变量的结果
- 如果语句给出不正确的结果
- 与 for 的结果混淆..在语句 JS 输出中
- Javascript 函数.可变结果.为什么未定义或没有 如果 else 语句函数
- Jquery 优化表的结果:两个或多个逻辑语句
- 在文本框中显示 if 语句的结果
- switch 语句以仅在项目类型更改时返回结果
- 剃刀 if 语句的奇怪结果
- 使用 Handlebars.js 处理 executeSql 语句的结果
- Javascript Switch 语句未提供正确的结果
- if 语句不起作用并显示相同的结果
- 我可以把两个骨髓动画序列组合成一个语句,仍然得到相同的结果吗
- 根据php-if/else语句的结果创建javascript操作
- I'm在if语句中使用小于比较器;然而,即使它不应该;t、 它的评估结果为false
- 为什么两个相同的语句返回不同的结果,只是用括号括住其中一个而不是另一个