雄辩的JavaScript第4章数组



这是我在这里的第一篇文章。我有一个小问题。法典:

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; // Why +2?
        table[index] += 1;
    }
    return table;
}
console.log(tableFor("pizza", JOURNAL));
// → [76, 9, 4, 1]

日志文件可以在这里找到。

我的问题是为什么会有+= index.当我运行代码时,它当然给了我正确的结果,但我不明白为什么+2+1?我看到 +1 给了我错误的结果。

感谢您的回复。

table数组输出看起来就像一个条件计数器。它有 4 个可能的索引,每个索引根据当前日记项目中找到的事件递增。

根据函数的外观,计数器表示以下内容(给定以下索引(:

0 - does not contain the given event or squirrel
1 - contains the given event but not squirrel
2 - contains squirrel but not the given event
3 - contains both the given event and squirrel

所以要具体回答,为什么+= 2?好吧,通过添加2索引最终将 23 ,表明上述两个条件之一。

index似乎是一个位集。如果你找到披萨但没有松鼠,你会得到0b01,如果你有一只松鼠但没有披萨,你会得到0b10,如果你找到两个,你会得到0b11,而你都不会得到0b00。披萨的值 21 需要与松鼠的值 20 区分开来。

更干净的代码可能使用了位运算符:

const entry = journal[i];
const index = (entry.events.includes(event)) << 0) | (entry.squirrel << 1);
table[index] += 1;

如果我没记错的话,那么table索引表示以下内容。

0: no pizza, no squirrel 
1: pizza, no squirrel
2: no pizza, squirrel
3: both

因此,如果您想正确定位这些索引,那么 Pizza 会+1索引位置,松鼠会将+2添加到索引位置

  • 如果没有披萨和松鼠 - 'index = 0'
  • 如果有披萨("索引+1"(而没有松鼠 - "索引= 1">
  • 如果没有披萨和松鼠("指数+2"( - "指数= 2">
  • 如果同时有披萨("索引 +1"(和松鼠("索引 +2"(-"索引 = 3">

最新更新