【问题标题】:Property of Function not increasing properly?函数的属性没有适当增加?
【发布时间】:2012-11-07 21:00:36
【问题描述】:

我正在练习一些不同的 JavaScript 技术,即函数属性。这让我有点摸不着头脑。

//property of the q0 function
q0.unique = 0;


function q0() {

return q0.unique++;

}

console.log(q0()); //returns 0 
console.log(q0()); //returns 1
console.log(q0()); //returns 2
console.log(q0()); //returns 3

第一次调用函数不应该返回 1 吗?为什么返回0? q0.unique 已经设置为 0 了吗?

【问题讨论】:

    标签: javascript post-increment


    【解决方案1】:

    增量运算符有两种:

    var++ // increment  the variable ---after--- the operation.  
    ++var // increment  the variable ---before-- the operation.
    

    例子:

    var x = 0;
    
    alert(x++) // 0
    alert(x)   // 1
    alert(++x) // 2
    

    【讨论】:

      【解决方案2】:

      您混淆了前增量和后增量。给定:

      var unique = 0;
      

      var x = unique++ 将分配 当前unique (0) 而var x = ++unique 将在递增后分配 unique 值 (1)。毕竟在这两种情况下unique 的值都是1

      你想要的是:

      function q0() {
        return ++q0.unique;
      }
      

      【讨论】:

        【解决方案3】:

        后缀自增运算符返回自增前的值。

        var a = 0;
        var b = a++;
        // now a==1 and b==0
        

        回忆它的最好方法是将a++读作give the value and then increment

        如果要返回增量后的值,使用

        return ++q0.unique;
        

        Reference

        【讨论】:

          【解决方案4】:

          如果您的代码是这样的,那就是:

          function q0() {
          
          return ++q0.unique;
          
          }
          

          后缀++返回当前值然后递增。带有前缀 ++ 的情况正好相反。

          【讨论】:

          • 啊,我明白了。除了帖子之外的前。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-12-09
          • 1970-01-01
          • 2011-10-23
          • 2020-04-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多