什么是波浪号做的时候它precedes一个前pression? [英] What does a tilde do when it precedes an expression?

查看:93
本文介绍了什么是波浪号做的时候它precedes一个前pression?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  VAR ATTR =〜'输入,textarea'.indexOf(target.tagName.toLowerCase())
           ? '值'
           :的innerHTML

看到它的答案,我以前从来没有见过。

这是什么意思?


解决方案

是<一个href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators?redirectlocale=en-US&redirectslug=Core_JavaScript_1.5_Reference/Operators/Bitwise_Operators\">bitwise即在翻转操作数的所有位运算符。

例如,如果您的号码是 1 的的 IEEE 754浮点数(如何对待JavaScript的数字)将...

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

所以操作数转换为32位整数(在JavaScript位运算符做到这一点)...

  0000 0000 0000 0000 0000 0000 0000 0001

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

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

  1111 1111 1111 1111 1111 1111 1111 1110


  

那么,什么是它的使用呢?当可能人会使用它吗?


它有相当多的用途。如果你正在编写低级的东西,它很方便(比如,我写在它使用的那一刻仿真器)。

这也是一个(一般)不清楚的的打开的indexOf()发现的返回值放入 truthy 的(同时使的未找到的作为的 falsy 的),人们常常用它来截断数字为32位(和删除其小数位的副作用通过加倍它,实际上是相同的 Math.floor()为正数)。

我说的不清楚的,因为它会立即不是它正在使用明显的东西。通常情况下,你希望你的code清楚地传达给其他人阅读。当使用可能的看起来很酷的,它通常是为自己好太聪明了。 :)

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

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

What does it mean?

解决方案

~ is a bitwise operator that 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...

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)...

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.

...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 (for example, I'm writing an emulator at the moment which uses it).

It's also a (generally) unclear trick to turn indexOf()'s found return value into truthy (while making not found as 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).

I say unclear because 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. :)

这篇关于什么是波浪号做的时候它precedes一个前pression?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆