Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript 中的位运算 #2

Open
sunhengzhe opened this issue Jul 15, 2017 · 1 comment
Open

javascript 中的位运算 #2

sunhengzhe opened this issue Jul 15, 2017 · 1 comment

Comments

@sunhengzhe
Copy link
Member

以前取随机数的方式一直是

const rIndex = Math.floor(Math.random() * arr.length);

实际上可以使用位运算代替 Math.floor

const rIndex = Math.random() * arr.length | 0;

这是因为要进行运算的值会被先转为有符号的 32 位整型。所以超过 32 位的整数会被截断,而小数部分则会被直接舍弃。

除此之外,还有哪些好用的位运算使用方式呢?

@sunhengzhe
Copy link
Member Author

  • 判断是否是奇数
n & 1 === 0
  • 两次 ~ 运算取代 Math.floor
~~3.14 // 3
  • 1 的左移实现 2 的 n 次方
1 << 3 // 2^3 = 8
1 << 4 // 2^4 = 16

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant