Knockout JS:计算平均回报率NaN?

时间:2014-04-19 21:46:11

标签: javascript html knockout.js ko.observablearray

背景

我正在构建我的第一个网络应用程序,一本成绩簿。我试图从scores的可观察数组计算平均得分。名为mean的平均值是一个可观察对象。 meanscores都属于该模型。

我不确定这里的问题是什么。我注意到在向控制台打印mean时打印的值是NaN或代码块。我的脚本以及控制台日志可以在这里看到:

http://jsbin.com/fehoq/20/edit

我想知道在观察中添加一个数字是否与我假设的一样简单,但我不确定正确的方法是什么。

1 个答案:

答案 0 :(得分:0)

在处理observable和可观察数组时,请确保正确读取和写入...

在这段代码中......

this.scores = ko.observableArray([79, 89]);
this.mean = ko.observable();

// ...

ko.utils.arrayForEach(_this.scores(), function (score) {
    _this.mean += score;
    console.log(score);
    console.log(_this.mean);
});
_this.mean = _this.mean / _this.scores.length;
console.log(_this.mean);
return _this.mean;

_this.mean += score会覆盖原始的可观察对象。相反它应该是_this.mean(_this.mean() + score)。这种情况发生在几个地方。

访问scores可观察数组也是如此。 _this.scores.length应为_this.scores().length

以下是应用更改的代码...

ko.utils.arrayForEach(_this.scores(), function (score) {
     _this.mean(_this.mean() + score);
     console.log(score);
     console.log(_this.mean());
});
_this.mean(_this.mean() / _this.scores().length);
console.log(_this.mean());
return _this.mean();
相关问题