按位运算和箭头函数return语句

Bitwise operation and arrow function return statement

我有一个字节,我想将剩余的位从第一位递增 1(上下文是一个小型康威生命游戏)。

示例:11 是 0000 1011:

  1. 我想增加101
  2. 5 + 1 = 6 是 110
  3. 将第一位重置为初始状态
  4. 字节现在是 0000 1101 即 13

问题:

const getBinaryRepresentation = (number) => {
    let str = "";
    for (let i = 7; i >= 0; i--) {
        ((number & (1 << i)) != 0) ? str += "1" : str += "0";
    }
    console.log(str)
}

let num = 5; 
getBinaryRepresentation(num) // 0000 0101
const addNeighbour = (num) => {
    const isAlive = num & 1;
    const neighbours = num >> 1;

    num = (neighbours + 1) << 1;
    if (isAlive === 1) num |= (1 << 0)
    return num;
}
num = addNeighbour(num);
getBinaryRepresentation(num) // 0000 0111

因为你不能对 javascript 中的简单值使用 byRef 你不能 return void 和改变函数外的变量。

不过,您可以通过重用变量来稍微优化一下函数:

const getBinaryRepresentation = (number) => {
  return console.log(number.toString(2).padStart(8, 0));
}

let num = 5;
getBinaryRepresentation(num) // 0000 0101
const addNeighbour = (num) => {
    const isAlive = num & 1;
    num >>= 1;
    num = (num + 1) << 1;
    return num | isAlive;
}
num = addNeighbour(num);
getBinaryRepresentation(num) // 0000 0111

Is there a way to make addNeighbour proceed as a void method (I couldn't find a way to not return num)?

没有。如果您不 return 结果,则无法将其分配回 num。并且您不能传递对 let num(或任何其他)变量的引用,该函数应该从中读取并存储到其中。

Is there a better way to perform addNeighbour operations

是的。在 second-least 有效位位置添加 1 与在最低位添加 2 相同。将您的代码替换为

num += 2;

换句话说,

  (((num >> 1) + 1) << 1) | (num & 1)
≡ (((num >> 1) << 1) + (1 << 1)) | (num & 1)
≡ ((num & ~1) + (1 << 1)) | (num & 1)
≡ ((num & ~1) | (num & 1)) + (1 << 1)
≡ num + (1 << 1)