我不完全理解为什么以下显示"悬挂"到最后.
var x = 'set';
var y = function ()
{
// WHAT YOU DON'T SEE -> var x;
// is effectively "hoisted" to this line!
if (!x)
{
// You might expect the variable to be populated at this point...it is not
// though, so this block executes
var x = 'hoisted';
}
alert(x);
}
//... and this call causes an alert to display "hoisted"
y();
Run Code Online (Sandbox Code Playgroud)
任何指针将不胜感激.
所以我想说我有一些代码:
//Javascript
var elements = [];
function addNumbah1(){
var i = 1;
elements.push(i);
}
function addNumbah2(){
var i = 2;
elements.push(i);
}
Run Code Online (Sandbox Code Playgroud)
这继续addNumbah999(),i每次声明变量是不好的形式?会破坏什么吗?我应该这样做:
//Javascript
var elements = [];
var i
function addNumbah1(){
i = 1;
elements.push(i);
}
function addNumbah2(){
i = 2;
elements.push(i);
}
Run Code Online (Sandbox Code Playgroud) 刚才,我看到了一些这样的代码:
if(condition){
var xx='sss';
}
//do something
if(condition){
console.info(xx);
}
Run Code Online (Sandbox Code Playgroud)
现在,我只是想知道为什么第二个if陈述有效?它如何访问xx变量,因为它是另一个if语句中定义的局部变量?