javascript - I can't understand this js question
某草草
某草草 2017-05-19 10:44:12
0
9
652
function foo() {
    var i = 0;
    return function() {
        console.log(i++);
    }
}

var f1 = foo(), f2 = foo();
f1();
f1();
f2();

为什么结果是0, 1, 0而不是1, 2, 1呢
某草草
某草草

reply all(9)
给我你的怀抱
console.log(i++)
// 相当于
console.log(i);
i = i+1;
console.log(++i)
// 相当于
i = i+1;
console.log(i);
过去多啦不再A梦

Do you think i is a global variable?
Since i is a local variable, what is the relationship between i in f1 and i in f2?

As for why it is 0, 1 instead of 1, 2.
That’s because i++ is actually i = i + 1;
console.log(i++), i is printed first, and then i = i + 1 is executed ;
If you change it to console.log(++i); then it will be 1 or 2.

小葫芦

This is the difference between i++ and ++i, i++ is quoted first and then incremented, ++i is first incremented and then quoted

PHPzhong
var a = 42;
a++; //42
a; //43

++a; //44
a; //44
漂亮男人

When f1 is executed for the first time, 0 is output. Because it is i++, i is output first and then added. When executed again, i is 1 at this time. Similarly, 2 is output. When f2 is executed, because i is 0, 0 is output. That is to say, the scopes of f1 and f2 are different, so the references of i are also different.

習慣沉默

f1() is execution

    function() {
        console.log(i++);
    }

And i is the internal variable of f1. After ++, it will naturally output 0, 1

You can understand it by just adding one line to your code

function foo() {
    var i = 0;
    console.log(i);
    return function() {
        console.log(i++);
    }
}

The newly added console.log will only be executed when var f1 = foo() and f1() will not be executed

大家讲道理

i++ is arithmetic first and then addition and subtraction, so it outputs 0 first and then changes to 1

阿神

Because ++ is a post-operation self-add operator. i will be incremented after completing this instruction.

小葫芦

The reason for

0 is that console.log will be executed first and then i will be incremented. However, the i in f1 and f2 are not related, and because of the closure, executing f1 again will get 1.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template