2017-07-16 24 views
0
function Counter() 
    { this.sum = 0; 
    this.count = 0; 
    } 

Counter.prototype.add = function(array){ 
array.forEach(function(entry){ 
this.sum+= entry; 
++this.count; 
},this); 
}; 

var obj = new Counter(); 
obj.add([2,5,9]); 
console.log(obj.count); 
// 3 
console.log(obj.sum); 
//16 

++符号在这里有什么作用? 我知道这是一个人为的例子,它是一个array.forEach(function()) 应用程序。但我似乎并没有明白这一点。请通读此代码。为什么它的输出是3和16我应该如何理解附加代码中的“array.forEach(function)”?

+2

*请通过此代码。为什么它的输出是3和16 * - 最好的一个来帮助你在这里是Chrome/Firefox中的JavaScript调试器。打开开发人员工具/ F12并尝试一下。 – niksofteng

+0

++此处的this.count相当于this.count = this.count + 1 – Avinash

回答

2

this[arg]是指“类”Counter的属性。 this.count是一些计数器,表示this.sum已增加了多少倍。 ++只是递增1

的东西。换句话说,如果一些变量foo0foo++是一样的foo = foo + 1

基本上它是这样的......

您传递[2, 5, 9]forEach遍历每个值。

第一次迭代:

this.sum = this.sum + 2 // => 2

this.count = this.count + 1 // => 1

第二次迭代:

this.sum = this.sum + 5 // => 2 + 5 = 7

this.count = this.count + 1 // => 1 + 1 = 2

最后一次迭代:

this.sum = this.sum + 7 // => 7 + 9 = 16

this.count = this.count + 1 // => 2 + 1 = 3

就这样,你会得到16和3。

1

您创建一个Counter对象:

var obj = new Counter(); 

您拨打Counter对象的add()函数的参数与数259的数组:

obj.add([2,5,9]); 

关于add()功能:

Counter.prototype.add = function(array){ 
    function(array){ 
    array.forEach(function(entry){ 
     this.sum+= entry; 
     ++this.count; 
    },this); 
    }; 

对于数组中的每个元素,所述forEach()功能使得两件事情:

  • 增量sum数目可变求和数组的每个元素:

    this.sum+= entry;

  • 增量count数字变量只要forEach()调用完成:

    ++this.count;

++this.count;是预先递增运算符。这意味着在此声明中计数是递增的。

在这种情况下,它不会改变任何内容,因为您不会在同一语句中使用增量结果。 您可以使用this.count++;

如果,例如,你会递增,输出在同一份声明中控制台这个新的价值,它将使意义:

var count = 0; 
console.log(++this.count); // display 1 

通过预增量,新的值将仅在未来体现声明:

var count = 0; 
console.log(this.count++); // display 0 
console.log(this.count); // display 1 
相关问题