迭代过程如何工作

时间:2018-08-20 19:11:52

标签: javascript arrays

我不明白以下循环的工作原理。我有这个绑定叫做《日记》,

var JOURNAL = [
  {"events":["carrot","exercise","weekend"],"squirrel":false},
  {"events":["bread","pudding","brushed teeth","weekend","touched tree"],"squirrel":false},
  {"events":["carrot","nachos","brushed teeth","cycling","weekend"],"squirrel":false}
];

以下代码循环遍历

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

哪种农产品

     // → [76, 9, 4, 1]

我的问题是跟踪生产输出。我现在尝试花一些时间研究它几个小时,但是我不明白。我需要有关此循环如何工作的详细说明。

2 个答案:

答案 0 :(得分:1)

对于每一行:

If "pizza" in events => increment table[index = 0 + 1]
else
If "squirrel" == true => increment table[index = 0 + 2]
else
If "pizza" in events AND "squirrel" == true => increment table[index = 0 + 1 + 2]
else
increment table[index = 0]

答案 1 :(得分:1)

返回表中的每个条目都是匹配不同条件组合的日记条目的总数。

  • 0 =没有条件匹配
  • 1 =日记帐分录的events数组包含给定的event
  • 2 =日记条目的squirrel属性为true。
  • 3 =两种条件都匹配。

因此,对于每个条目,它首先将index设置为0,这没有任何匹配之处。然后,它为要测试的每个条件添加12。如果都为真,则它们总计为3

如果存在第三个条件,它将为此添加4。每个连续的增量应该是2的下一个幂。得到的索引是每个匹配条件的1位的位掩码。