背景
我试图在第二个数组 B 中检查数组 A 中是否存在一个值。每个值都是一个可观察的数字。每个可观察的数字都包含在一个可观察的数组中。比较总是返回 -1,这是不正确的(只要 A 和 B 中的值重叠)。因此,我的逻辑或语法有问题,但我一直无法弄清楚在哪里。
JSBin (full project): http://jsbin.com/fehoq/190/edit
JS
//set up my two arrays that will be compared
this.scores = ko.observableArray();
//lowest is given values from another method that splices from scores
this.lowest = ko.observableArray();
//computes and returns mean of array less values in lowest
this.mean = (function(scores,i) {
var m = 0;
var count = 0;
ko.utils.arrayForEach(_this.scores(), function(score) {
if (!isNaN(parseFloat(score()))) {
//check values
console.log(score());
// always returns -1
console.log(_this.lowest.indexOf(score()));
//this returns an error, 'not a function'
console.log(_this.lowest()[i]());
//this returns undefined
console.log(_this.lowest()[i]);
//only do math if score() isn't in lowest
// again, always returns -1, so not a good check
if (_this.lowest.indexOf(score())<0) {
m += parseFloat(score());
count += 1;
}
}
});
// rest of the math
if (count) {
m = m / count;
return m.toFixed(2);
} else {
return 'N/A';
}
});
更新
@Major Byte 指出 mean() 是在任何东西被推到lowest
之前计算的,因此我得到 undefined
的原因。如果这是真的,那么确保 mean() 将根据对 lowest
的更改进行更新的最佳方法可能是什么?
最佳答案
您真的可以使用计算的均值
this.mean = ko.computed(
function() {
var sum = 0;
var count = 0;
var n = 0;
for(n;n < _this.scores().length;n++)
{
var score = _this.scores()[n];
if (_this.lowest.indexOf(score)<0) {
sum += parseFloat(score());
count++;
}
}
if (count > 0) {
sum = sum / count;
return sum.toFixed(2);
} else {
return 'N/A';
}
});
这将在您添加到 lower()、scores() 和更改 scores() 时触发。
更新:
忘了说我也改变了一些重要的东西。来自您的原始代码:
this.dropLowestScores = function() {
ko.utils.arrayForEach(_this.students(), function(student){
var comparator = function(a,b){
if(a()<b()){
return 1;
} else if(a() > b()){
return -1;
} else {
return 0;
}
};
var tmp = student.scores().sort(comparator).slice(0);
student.lowest = ko.observableArray(tmp.splice((tmp.length-2),tmp.length-1));
});
};
除了将 comparator
移到 dropLowestScores
函数之外,我还更改了以下行:
student.lowest = ko.observableArray(tmp.splice((tmp.length-2),tmp.length-1));
到
student.lowest(tmp.splice((tmp.length-2),tmp.length-1));
student.lowest
是一个 observable 数组,无需再次将其定义为 observableArray,事实上这实际上打破了计算的 mean
。 (根据我之前的评论对 Drop Lowest Scores 的更正已在此处省略)。
关于javascript - knockout : More confusion with indexOf returning -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23572246/