【问题标题】:Can someone explain the output of this fiddle? [duplicate]有人可以解释这个小提琴的输出吗? [复制]
【发布时间】:2014-11-18 13:27:49
【问题描述】:

我有这个代码。我已经写了我期望作为正确输出的 'i' (以 cmets 为单位)的值。但是输出/警报是不同的。

小提琴:http://jsfiddle.net/e2jbno4a/
代码:

var i = 10;

function outer() {
    alert(i); // 10
    var i = 5;
    alert(i); // 5
    function inner() {
        var i = 20;
    }
    inner();
    alert(i); // 5
    if (1) {
        var i = 30;
    }
    alert(i); // 5
    setTimout(function () {
        alert(i); // 5
    }, 100);
}

outer();

有人可以告诉我输出的原因吗?还是只是解释具体概念的指针?

【问题讨论】:

标签: javascript web concept


【解决方案1】:

所以,一步一步来:

var i = 10;

function outer() {
    alert(i); // undefined
    var i = 5;
    alert(i); // 5 (i now references the `i` in this function's scope.)
    function inner() {
        var i = 20; // (The `20` is only available in the scope of `inner`)
    }
    inner();
    alert(i); // 5 (So, this `i` still references the `var i = 5;` one)
    if (1) {
        var i = 30;
    }
    alert(i); // 30 (This one actually alerts `30`. There is no block scope in JS)
    setTimeout(function () {
        alert(i); // 5 (This will log `30`, you made a typo in the `setTimeout` call)
    }, 100);
}

outer();

【讨论】:

  • 答案是错误的。第一个将输出未定义。请参阅顶部标记的重复问题的示例“8”。
  • 修复了,@halkujabra。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多