为什么函数会返回这些值?

时间:2015-04-04 11:42:58

标签: javascript function

此函数对来自a file的事件进行计数,并将它们存储在数组中。

function hasEvent(event, entry) {
  return entry.events.indexOf(event) != -1;
}

function tableFor(event, journal) {
  var table = [0, 0, 0, 0];
  for (var i = 0; i < journal.length; i++) {
    var entry = journal[i], index = 0;
    if (hasEvent(event, entry)) index += 1; //9
    if (entry.squirrel) index += 2; //4
    table[index] += 1;
  }
  return table;
}
console.log(tableFor("pizza", JOURNAL));

为什么此函数会返回//76, 9, 4, 1?数字应为//74, 10, 5, 1

我认为该功能从零开始计算,但我不这么认为。

1 个答案:

答案 0 :(得分:-1)

最好的方法是实施......

events = 90,

pizza = 10,

松鼠:真= 5,

pizza and squirrel:true = 1,所以我们需要在实现中休息-2

90 - 10 - 5 - 1 = 74

&#13;
&#13;
function hasEvent(event, entry) {
  return entry.events.indexOf(event) != -1;
}

function tableFor(event, journal) {
  var table = [0, 0, 0, 0];
  for (var i = 0; i < journal.length; i++) {
    var entry = journal[i];
    if(hasEvent(event, entry) && entry.squirrel) table[3] += 1; //1
    if(entry.squirrel) table[2] += 1; //5
    if(hasEvent(event, entry)) table[1] += 1; //10
    if(!(hasEvent(event, entry) || entry.squirrel)) table[0] += 1; //76
    // xor
    if(hasEvent(event, entry) && entry.squirrel) table[0] -= 2; //74
  }
  return table;
}
console.log("Expected: 74,10,5,1")
console.log("Calculated: " + tableFor("pizza", JOURNAL));
&#13;
<script src="http://eloquentjavascript.net/code/jacques_journal.js"></script>
&#13;
&#13;
&#13;