1

我在咖啡脚本的小书中找到了这个

!!~ string.indexOf "test"

我测试

~-1 == 0
~0  == -1
~3 == -4
~-2 == 1

那么这里到底发生了什么以及为什么返回,~0唯一产生的价值吗?-1-10

4

1 回答 1

3

In two's complement integers, -1 is a sequence of all 1-bits. The ~ bitwise operator:

Inverts the bits of its operand.

Inverting the bits in a sequence of 1-bits gives you a sequence of 0-bits and a sequence of 0-bits is the integer 0. So ~i is zero if and only if i === -1.

String#indexOf:

[...] returns -1 if the value is not found

Putting those two things together tells us that this:

~ string.indexOf "test"

is zero if and only if "test" is not present in string. Then we add the !! "cast to boolean" trick and the fact that 0 is the only integer that is falsey in JavaScript and we have:

!!~ string.indexOf "test"

being true if "test" appears in string and false otherwise; or, in sensible and readable code, that's the same as:

string.indexOf("test") != -1

If the book is actually suggesting that you write code like that then you should burn that book and find a better one. Using all that bit twiddling is just the sort of "cleverness" that will make everyone maintaining your code hate you.

于 2013-09-05T18:29:21.430 回答