在Javascript中做什么~~(“双波浪”)? [英] What does ~~ ("double tilde") do in Javascript?

查看:124
本文介绍了在Javascript中做什么~~(“双波浪”)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天正在查看一个在线游戏物理库,并遇到了~~运算符。我知道单个〜是一个按位NOT,是否会使~~一个NOT的NOT,它会返回相同的值,不是吗?

I was checking out an online game physics library today and came across the ~~ operator. I know a single ~ is a bitwise NOT, would that make ~~ a NOT of a NOT, which would give back the same value, wouldn't it?

推荐答案

它会删除小数点后的所有内容,因为按位运算符会将其操作数隐式转换为带符号的32位整数。这适用于操作数是(浮点)数字还是字符串,结果是数字。

It removes everything after the decimal point because the bitwise operators implicitly convert their operands to signed 32-bit integers. This works whether the operands are (floating-point) numbers or strings, and the result is a number.

换句话说,它产生:

function(x) {
  if(x < 0) return Math.ceil(x);
  else return Math.floor(x);
}

仅当 x 介于 - (2 < sup> 31 )和2 31 - 1.否则,将发生溢出并且数字将环绕。

only if x is between -(231) and 231 - 1. Otherwise, overflow will occur and the number will "wrap around".

这可能被认为有用的是将函数的字符串参数转换为数字,但由于存在溢出的可能性以及与非整数一起使用不正确,我不会那样使用它,除了code golf( ie 以牺牲可读性和健壮性为代价,无意义地删除程序源代码中的字节。我会改用 + x Number(x)

This may be considered useful to convert a function's string argument to a number, but both because of the possibility of overflow and that it is incorrect for use with non-integers, I would not use it that way except for "code golf" (i.e. pointlessly trimming bytes off the source code of your program at the expense of readability and robustness). I would use +x or Number(x) instead.

数字-43.2,例如:

The number -43.2, for example is:

-43.2 10 = 11111111111111111111111111010101 2
-43.210 = 111111111111111111111111110101012

作为签名(二进制补码)32位二进制数。 (JavaScript忽略小数点后的内容。)反转位给出:

as a signed (two's complement) 32-bit binary number. (JavaScript ignores what is after the decimal point.) Inverting the bits gives:

NOT -43 10 = 00000000000000000000000000101010 2 = 42 10
NOT -4310 = 000000000000000000000000001010102 = 4210

再次反转给出:

NOT 42 10 = 11111111111111111111111111010101 2 = -43 10
NOT 4210 = 111111111111111111111111110101012 = -4310

这与 Math.floor(-43.2),因为负数被舍入为零,而不是远离它。 (地板函数,等于-44,总是向下舍入到下一个较低的整数,无论​​数字是正数还是负数。)

This differs from Math.floor(-43.2) in that negative numbers are rounded toward zero, not away from it. (The floor function, which would equal -44, always rounds down to the next lower integer, regardless of whether the number is positive or negative.)

这篇关于在Javascript中做什么~~(“双波浪”)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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