返回值不是预期的 - 关闭

Returned value not expected - closures

我不明白为什么是returns0,应该是加1,闭包有什么我不知道的地方吗?

 let i = 0;
    const getRenderValue = function() {

      return i++;
    };
    const Component = function() {
      let hello = getRenderValue();
      console.log(hello); // return 0, expected value 1
    };
    Component();

您的闭包确实将 i 的值增加了 1。如果您使用 console.log(i); 而不是 console.log(hello);,您会在屏幕上看到预期的 1

您的闭包 return 是 i 之前 的值,因为它 return 是 i++ 的增量:它是后缀增量 i++ 的 属性,它在增量之前而不是之后 returns i。如果要 return 更改后的值,请使用前缀增量 ++i