Javascript 波浪号在表达式之前有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12299665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:38:58  来源:igfitidea点击:

What does a tilde do when it precedes an expression?

javascriptsyntaxbit-manipulation

提问by wwaawaw

var attr = ~'input,textarea'.indexOf( target.tagName.toLowerCase() )
           ? 'value'
           : 'innerHTML'

I saw it in an answer, and I've never seen it before.

我在一个答案中看到了它,我以前从未见过它。

What does it mean?

这是什么意思?

回答by alex

~is a bitwise operatorthat flips all bits in its operand.

~是一个按位运算符,用于翻转其操作数中的所有位。

For example, if your number was 1, its binary representation of the IEEE 754 float(how JavaScript treats numbers) would be...

例如,如果您的数字是1,则其IEEE 754 浮点数(JavaScript 如何处理数字)的二进制表示将是...

0011 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000

So ~converts its operand to a 32 bit integer (bitwise operators in JavaScript do that)...

因此~将其操作数转换为 32 位整数(JavaScript 中的按位运算符会这样做)...

0000 0000 0000 0000 0000 0000 0000 0001

If it were a negative number, it'd be stored in 2's complement: invert all bits and add 1.

如果它是一个负数,它将存储在 2 的补码中:反转所有位并加 1。

...and then flips all its bits...

...然后翻转所有位...

1111 1111 1111 1111 1111 1111 1111 1110

So what is the use of it, then? When might one ever use it?

那么它有什么用呢?什么时候可以使用它?

It has a quite a few uses. If you're writing low level stuff, it's handy. If you profiled your application and found a bottleneck, it could be made more performant by using bitwise tricks (as one possibletool in a much bigger bag).

它有很多用途。如果你在写低级的东西,它很方便。如果您分析了应用程序并发现了瓶颈,则可以通过使用按位技巧(作为一种可能的工具放在更大的包中)来提高其性能。

It's also a (generally) unclear trickto turn indexOf()'s foundreturn value into truthy(while making not foundas falsy) and people often use it for its side effect of truncating numbers to 32 bits (and dropping its decimal place by doubling it, effectively the same as Math.floor()for positive numbers).

将' found返回值转换为值(同时使not found)也是一个(通常)不清楚的技巧,人们经常使用它来将数字截断为 32 位(并通过将其加倍来删除小数位)的副作用,实际上与正数相同)。indexOf()Math.floor()

I say unclearbecause it's not immediately obvious what it is being used for. Generally, you want your code to communicate clearly to other people reading it. While using ~may look cool, it's generally too clever for its own good. :)

我说不清楚,因为它的用途并不是很明显。通常,您希望您的代码与阅读它的其他人清楚地交流。虽然使用~可能看起来很酷,但它通常太聪明了。:)

It's also less relevant now that JavaScript has Array.prototype.includes()and String.prototype.includes(). These return a boolean value. If your target platform(s) support it, you should prefer this for testing for the existence of a value in a string or array.

现在 JavaScript 具有Array.prototype.includes()和,它也不太相关String.prototype.includes()。这些返回一个布尔值。如果您的目标平台支持它,您应该更喜欢使用它来测试字符串或数组中是否存在值。

回答by Pointy

Using it before an indexOf()expression effectively gives you a truthy/falsy result instead of the numeric index that's directly returned.

indexOf()表达式之前使用它可以有效地为您提供真/假结果,而不是直接返回的数字索引。

If the return value is -1, then ~-1is 0because -1is a string of all 1 bits. Any value greater than or equal to zero will give a non-zero result. Thus,

如果返回值是-1,则~-10因为-1是全 1 位的字符串。任何大于或等于零的值都将给出非零结果。因此,

if (~someString.indexOf(something)) {
}

will cause the ifcode to run when "something" is in "someString". If you try to use .indexOf()as a boolean directly, then that won't work because sometimes it returns zero (when "something" is at the beginning of the string).

if当“something”在“someString”中时,将导致代码运行。如果您尝试.indexOf()直接用作布尔值,那么这将不起作用,因为有时它返回零(当“某物”位于字符串的开头时)。

Of course, this works too:

当然,这也有效:

if (someString.indexOf(something) >= 0) {
}

and it's considerably less mysterious.

而且它的神秘性要低得多。

Sometimes you'll also see this:

有时你还会看到这个:

var i = ~~something;

Using the ~operator twice like that is a quick way to convert a string to a 32-bit integer. The first ~does the conversion, and the second ~flips the bits back. Of course if the operator is applied to something that's cannot be converted to a number, you get NaNas a result. (edit— actually it's the second ~that is applied first, but you get the idea.)

~像这样使用运算符两次是将字符串转换为 32 位整数的快速方法。第一个~进行转换,第二个~将位翻转回来。当然,如果运算符应用于无法转换为数字的内容,您就会得到NaN结果。(编辑- 实际上它~是第一个应用的第二个,但你明白了。)

回答by zangw

The ~is Bitwise NOT Operator, ~xis roughly the same as -(x+1). It is easier to understand, sort of. So:

~按位NOT运算符~x是大致相同的-(x+1)。它更容易理解,有点。所以:

~2;    // -(2+1) ==> -3

Consider -(x+1). -1can perform that operation to produce a 0.

考虑-(x+1)-1可以执行该操作以生成0.

In other words, ~used with a range of number values will produce a falsy (coerce to falsefrom 0) value only for the -1input value, otherwise, any other truthy value.

换句话说,~与一系列数值一起使用将只为输入值产生一个假(强制为falsefrom 0-1值,否则,任何其他真值。

As we know, -1is commonly called a sentinel value. It is used for many functions that return >= 0values for successand -1for failurein C language. Which the same rule of return value of indexOf()in JavaScript.

众所周知,-1通常称为哨兵值。它用于返回许多功能>= 0的值的成功-1失败的C语言编写。indexOf()JavaScript 中的返回值规则相同。

It is common to check of presence/absence of a substring in another string in this way

以这种方式检查另一个字符串中子字符串的存在/不存在是很常见的

var a = "Hello Baby";

if (a.indexOf("Ba") >= 0) {
    // found it
}
if (a.indexOf("Ba") != -1) { 
    // found it
}

if (a.indexOf("aB") < 0) { 
    // not found
}
if (a.indexOf( "aB" ) == -1) { 
    // not found
}

However, it would be more easily to do it through ~as below

但是,~按照以下方式进行操作会更容易

var a = "Hello Baby";

~a.indexOf("Ba");         // -7   -> truthy
if (~a.indexOf("Ba")) {   // true
    // found it
}

~a.indexOf("aB");         // 0    -> falsy
!~a.indexOf("aB");        // true
if (!~a.indexOf( "aB" )) {  // true
    // not found
}

You Don't Know JS: Types & Grammar by Kyle Simpson

你不知道的 JS:类型和语法 作者:Kyle Simpson

回答by Jorge Bucaran

~indexOf(item)comes up quite often, and the answers here are great, but maybe some people just need to know how to use it and "skip" the theory:

~indexOf(item)经常出现,这里的答案很好,但也许有些人只需要知道如何使用它并“跳过”理论:

   if (~list.indexOf(item)) {
     // item in list
   } else {
     // item *not* in list
   }

回答by Dana Woodman

For those considering using the tilde trick to create a truthyvalue from an indexOfresult, it is more explicit and has less magic to instead use the includesmethod on String.

对于那些考虑使用波浪号技巧从结果中创建一个值的人来说indexOf,使用includesonString方法更加明确并且没有那么神奇。

'hello world'.includes('hello') //=> true
'hello world'.includes('kittens') //=> false

Note that this is a new standard method as of ES 2015 so it won't work on older browsers. In cases where that matters, consider using the String.prototype.includes polyfill.

请注意,这是 ES 2015 的新标准方法,因此它不适用于旧浏览器。如果这很重要,请考虑使用String.prototype.includes polyfill

This feature is also available for arrays using the same syntax:

此功能也可用于使用相同语法的数组:

['apples', 'oranges', 'cherries'].includes('apples') //=> true
['apples', 'oranges', 'cherries'].includes('unicorns') //=> false

Here is the Array.prototype.includes polyfillif you need older browser support.

如果您需要旧浏览器支持,这里是Array.prototype.includes polyfill