简体   繁体   English

Javascript语法:带“<<”或“>>”的变量声明

[英]Javascript syntax: variable declaration with “<<” or “>>”

I had a look at Jason Davies's Word Cloud source on Github and within the index.js there are some variables that are declared like this: 在Githubindex.js中查看了Jason Davies的Word Cloud源代码,其中有一些变量声明如下:

cw = 1 << 11 >> 5,
ch = 1 << 11;

I noticed this pattern: value before "<<" multiplies the value after "<<"; 我注意到了这种模式:“<<”之前的值乘以“<<”之后的值;
value after "<<" is a 2 to the power of the value specified; “<<”之后的值是指定值的2的幂;
value after ">>" (following "<<") divides that number before (which is also 2 two the power of the value); “>>”之后的值(在“<<”之后)除以前的那个数字(也就是值2的2);

I was curious: 我很好奇:

  1. in general what are the uses for this type of declaration and where does it come from 一般来说,此类声明的用途是什么,它来自何处

  2. how does it add value to the code in the rest of the Jason Davies' layout? 它如何为Jason Davies其余部分的代码增加价值?

See this link 看到这个链接

Basically, << and >> do bit-wise shifts. 基本上, <<>>做了逐位转换。 If you do a << b , it will represent a as a number in base 2 (0s and 1s) and shift all the digits to the left by b positions. 如果你做a << b ,它将代表a在基地2(0和1)一个数字,所有的数字转移到由左b位置。 This is mathematically equivalent to 这在数学上等同于

a * 2^b

The >> is the same principle, but it shifts to the right. >>是相同的原则,但它向右移动。 It's almost analogous to a division by a factor of 2, but there's a special case when the intial number is odd: it floors the result. 它几乎类似于除法因子2,但是当初始数字是奇数时有一个特殊情况:它将结果置于底层。

⌊(a / 2^b)⌋

If you have 1 << 11 >> 5 , the left and right shifts cancel each other, we end up in reality with 如果你有1 << 11 >> 5 ,那么左右移动相互抵消,我们最终实现了

1 << 6 === 64 === 1 * 2^6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM