Comments (5)
undefined
11
var
在 if
里面,会提前到块级作用域的开始,相当于:
var x;
var y = 10;
if (!(x in window)) {
x = 10;
} else {
++y;
}
alert(x);
alert(y);
from frontend-interview.
var x = 10; -> var x ; x = 10;
from frontend-interview.
输出undefined和11,其中x的值为undefined,y的值为11。
原因:变量提升,对式子进行转换后得出:
var y;
var x;
y = 10;
if (!(x in window)) {
x = 10;
} else {
++y;
}
alert(x);
alert(y);`
然后因为,此时的x在全局环境被声明,所以!(x in window)
为false,不执行x的赋值,然后执行++y,得出y值为11,x值为undefined;
from frontend-interview.
因为js没有块级作用域,以及存在变量提升。
这里补充另一种情况:函数的变量提升:
foo(); // foo
bar(); //bar is not defined
function foo() {
console.log('foo');
}
bar = function () {
console.log('bar');
};
from frontend-interview.
学习到了。还以为没有满足条件var 不会声明提前了。get
from frontend-interview.
Related Issues (20)
- JS 作用域链相关问题 HOT 5
- JS 作用域、原型链 HOT 3
- 重复声明两个函数会怎样? HOT 4
- ES5中“严格模式”与“非严格模式”的区别? HOT 3
- ajax请求序列化问题 HOT 5
- 循环/闭包/setTimeout/Promise 综合 HOT 1
- 服务端如何区分不同的用户 HOT 4
- 使用ES6实现该方法 HOT 13
- dom操作相关 HOT 7
- 什么是FP?与OOP的关系?
- 为何会出现浏览器兼容性问题?如何解决? HOT 2
- 前端性能优化 HOT 2
- JavaScript 分组 HOT 13
- 自适应和响应式有什么区别和联系
- 如何实现深拷贝? HOT 1
- 两个js数组相关题目 HOT 7
- 面试题汇总
- jrg interview questions HOT 7
- 实现一个深拷贝 HOT 8
- 宏任务微任务题 HOT 6
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from frontend-interview.