相关疑难解决方法(0)

'悬挂'JavaScript变量

我不完全理解为什么以下显示"悬挂"到最后.

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 hoisting

31
推荐指数
2
解决办法
2720
查看次数

如果我多次声明相同的变量,我会有任何问题吗?

所以我想说我有一些代码:

//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)

javascript variables

5
推荐指数
1
解决办法
8932
查看次数

为什么这在javascript中有效?

刚才,我看到了一些这样的代码:


if(condition){
    var xx='sss';   
}
//do something

if(condition){
    console.info(xx);
}
Run Code Online (Sandbox Code Playgroud)

现在,我只是想知道为什么第二个if陈述有效?它如何访问xx变量,因为它是另一个if语句中定义的局部变量?

javascript scope

4
推荐指数
1
解决办法
212
查看次数

标签 统计

javascript ×3

hoisting ×1

scope ×1

variables ×1