`Math.trunc` VS`| 0` VS`<< 0` VS`>> 0` VS`&放大器; -1` VS`^ 0` [英] `Math.trunc` vs `|0` vs `<<0` vs `>>0` vs `&-1` vs `^0`

查看:226
本文介绍了`Math.trunc` VS`| 0` VS`<< 0` VS`>> 0` VS`&放大器; -1` VS`^ 0`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现,在ES6有一个新的数学方法: Math.trunc

我看了它在 MDN文章描述,它听起来就像使用 | 0

此外,<< 0 >> 0 &放-1 ^ 0 也在做类似的事情(感谢@kojiro&安培; @Bergi)。

一些测试后,似乎唯一的区别是:


  • Math.trunc 收益 -0 在区间数( - 1, - 0] 位运算符 0

  • Math.trunc 收益 NaN的与非数字。位运算符返回 0

是否有更多的差异(其中所有的人)?


  N | Math.trunc |位运算符
----------------------------------------
42.84 | 42 | 42
13.37 | 13 | 13
0.123 | 0 | 0
0 | 0 | 0
-0 | -0 | 0
-0.123 | -0 | 0
-42.84 | -42 | -42
为NaN |为NaN | 0
富|为NaN | 0
无效(0)|为NaN | 0


解决方案

如何 Math.trunc(Math.pow(2,31)) Math.pow(2,31)| 0

位运算是在符号的32位整数进行。所以,当你做Math.pow(2,31)你在比特10000000000000000000000000000000这种重新presentation。因为这个数字已被转换为符号的32位的形式,我们现在的符号位的位置有一个1。这意味着,我们在签订的32位形式寻找一个-eve数。然后,当我们做位或为0,我们得到符号32位形式同样的事情。在十进制是-2147483648。

边注:在签约的32位形成可以被重新二进制psented为$ P $是[10000000000000000000000000000000,01111111111111111111111111111111]小数的范围。在十进制(基数为10)这个范围是[-2147483648,2147483647]。

I have just found that in ES6 there's a new math method: Math.trunc.

I have read its description in MDN article, and it sounds like using |0.

Moreover, <<0, >>0, &-1, ^0 also do similar things (thanks @kojiro & @Bergi).

After some tests, it seems that the only differences are:

  • Math.trunc returns -0 with numbers in interval (-1,-0]. Bitwise operators return 0.
  • Math.trunc returns NaN with non numbers. Bitwise operators return 0.

Are there more differences (among all of them)?


n      | Math.trunc | Bitwise operators
----------------------------------------
42.84  | 42         | 42
13.37  | 13         | 13
0.123  | 0          | 0
0      | 0          | 0
-0     | -0         | 0
-0.123 | -0         | 0
-42.84 | -42        | -42
NaN    | NaN        | 0
"foo"  | NaN        | 0
void(0)| NaN        | 0

解决方案

How about Math.trunc(Math.pow(2,31)) vs. Math.pow(2,31) | 0

Bitwise operations are performed on signed 32-bit integers. So, when you do Math.pow(2, 31) you get this representation in bits "10000000000000000000000000000000". Because this number has to be converted to signed 32-bit form, we now have a 1 in the sign bit position. This means that we are looking at a -eve number in signed 32-bit form. Then when we do the bitwise OR with 0 we get the same thing in signed 32-bit form. In decimal it is -2147483648.

Side note: In signed 32-bit form the range of decimals that can be represented in binary for is [10000000000000000000000000000000, 01111111111111111111111111111111]. In decimal (base 10) this range is [-2147483648, 2147483647].

这篇关于`Math.trunc` VS`| 0` VS`&LT;&LT; 0` VS`&GT;&GT; 0` VS`&放大器; -1` VS`^ 0`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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