关于Javascript提升的问题 [英] Questions on Javascript hoisting
本文介绍了关于Javascript提升的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我读到有关Javascript提升的内容时,我尝试了以下内容。我不确定为什么第一个和第二个输出不同。提前致谢。 (我甚至不确定这与吊装有关。)
While I was reading about Javascript hoisting, I tried the following. I am not sure why the first one and second one output differently. Thanks in advance. (I am not even sure that this is related to hoisting. )
var me = 1;
function findme(){
if(me){
console.log( me );//output 1
}
console.log( me ); //output 1
}
findme();
但是以下输出未定义。
However the followings output undefined.
var me = 1;
function findme(){
if(me){
var me = 100;
console.log(me);
}
console.log(me);
}
findme();
// undefined
推荐答案
变量声明被提升到每个函数的顶部,但值 assignments 保持原样。所以第二个例子运行如下:
Variable declarations get hoisted to the top of every function, but the value assignments stay where they are. So the second example is run like this:
var me = 1;
function findme () {
var me; // (typeof me === 'undefined') evaluates to true
if (me) { // evaluates to false, doesn't get executed
me = 100;
console.log(me);
}
console.log(me);
}
findme();
这篇关于关于Javascript提升的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文