2012-11-19 119 views
1

我正在练习一些各种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?

回答

3

如果你的代码是这将是正确的:

function q0() { 

return ++q0.unique; 

} 

的后缀++返回当前值然后增量。以前缀++这是相反的方式。

+0

啊,我明白了。除帖子之外的预先。 – Sethen

2

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

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

的最好方法调用它是阅读a++give the value and then increment

如果你想在增量后返回值,使用

return ++q0.unique; 

Reference

1

你是混淆前和增量后。鉴于:

var unique = 0; 

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

你想要的是:

function q0() { 
    return ++q0.unique; 
} 
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