javascript 这行波浪号在做什么?

What is the tilde doing in this line of javascript?

我正在尝试理解这行代码。减号和波浪号对 r[e] 做了什么?:

r = {}
for (e of s)
    r[e] = -~r[e] // What is this specific line assigning?

for (e in r)
    if (r[e] == 1)
        return e
return '_'

这段代码解决的问题是这样的(具体行有注释):

Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.

我理解除了评论的那一行之外的其他行。

Tilde 是一个 unary operator,它将表达式放在它的右边,对其执行这个小算法

-(N+1) // N is the expression right to the tilde

所以在你的代码中它是递增 r[e] 1(因为双重否定)。

请参阅以下示例:

console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0);  // -1
console.log(~1);  // -2
console.log(~2);  // -3

波浪号是 NOT 运算的按位运算符。

它接受一个数字作为操作数,将其转换为32位整数(参考IEEE_754-1985并翻转所有位。0变为1,1变为0。

例如,如果数字 5 表示为

00000000 00000000 00000000 00000101

上面的数字~5,翻转了位

11111111 11111111 11111111 11111010

~5的十进制值为(-6)。这也称为 2 的补码。由于表示 JavaScript 中数字符号的最高有效位被翻转,因此符号将始终改变。 2 的补码导致 X 的值变为 -(X+1)

引擎等某些应用程序使用按位数据结构,而按位运算在其中发挥作用。

  • 按位或 (|)
  • 按位与 (&)
  • 按位非 (~)
  • 按位异或 (^)
  • 按位左移 (<<)
  • 按位右移 (>>)