背景

我试图检查第二个数组B中数组A中是否存在值。每个值都是一个可观察的数字。每个可观察数包含在一个可观察数组中。比较总是返回-1,这是不正确的(因为A和B中的值重叠)。因此,我的逻辑或语法有问题,但是我无法弄清楚哪里。


  JSBin(完整项目):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。如果这是真的,那么确保根据lowest的更改更新mean()的最佳方法是什么?

最佳答案

您真的可以对mean使用一个计算值

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()时,将触发此操作。

obligatory jsfiddle

更新:
忘了提及我也改变了一些至关重要的事情。从您的原始代码:

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是一个可观察数组,无需再次将其定义为observableArray,实际上会破坏计算出的mean。 (此处未列出根据我之前的评论对“最低分数”的更正)。

关于javascript - knockout :indexOf返回-1时更加困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23572246/

10-12 12:51
查看更多