我应该在 JavaScript 中的什么地方使用按位运算符?

新手上路,请多包涵

我读过 “什么是按位运算符?” ,所以我知道 什么是 按位运算符,但我仍然不清楚如何使用它们。任何人都可以提供任何实际示例,说明按位运算符在 JavaScript 中的用处吗?

谢谢。

编辑:

只是深入研究 jQuery 源代码,我发现了几个使用按位运算符的地方,例如:(只有 & 运算符)

 // Line 2756:
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));

// Line 2101
var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;

原文由 James 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 302
2 个回答

例子:

解析十六进制值以获得 RGB 颜色值。

 var hex = 'ffaadd';
var rgb = parseInt(hex, 16); // rgb is 16755421

var red   = (rgb >> 16) & 0xFF; // returns 255
var green = (rgb >> 8) & 0xFF;  // 170
var blue  = rgb & 0xFF;     // 221

原文由 Mark 发布,翻译遵循 CC BY-SA 3.0 许可协议

我在生产脚本中 大量 使用按位运算符进行数字转换,因为有时它们比它们的 MathparseInt 等价物快得多。

我必须付出的代价是 代码的可读性。所以我通常在开发中使用 Math ,在生产中按位使用。

您可以在 jsperf.com 上找到一些性能技巧

如您所见,浏览器多年来没有优化 Math.ceilparseInt 所以我预测按位方式将来也会更快更短地做事。

关于SO的一些进一步阅读……


奖金: 备忘单 | 0 :一种将任何东西转换为整数的简单快捷的方法:

 ( 3|0 ) === 3;             // it does not change integers
( 3.3|0 ) === 3;           // it casts off the fractional part in fractionalal numbers
( 3.8|0 ) === 3;           // it does not round, but exactly casts off the fractional part
( -3.3|0 ) === -3;         // including negative fractional numbers
( -3.8|0 ) === -3;         // which have Math.floor(-3.3) == Math.floor(-3.8) == -4
( "3"|0 ) === 3;           // strings with numbers are typecast to integers
( "3.8"|0 ) === 3;         // during this the fractional part is cast off too
( "-3.8"|0 ) === -3;       // including negative fractional numbers
( NaN|0 ) === 0;           // NaN is typecast to 0
( Infinity|0 ) === 0;      // the typecast to 0 occurs with the Infinity
( -Infinity|0 ) === 0;     // and with -Infinity
( null|0 ) === 0;          // and with null,
( (void 0)|0 ) === 0;      // and with undefined
( []|0 ) === 0;            // and with an empty array
( [3]|0 ) === 3;           // but an array with one number is typecast to number
( [-3.8]|0 ) === -3;       // including the cast off of the fractional part
( [" -3.8 "]|0 ) === -3;   // including the typecast of strings to numbers
( [-3.8, 22]|0 ) === 0     // but an Array with several numbers is typecast to 0
( {}|0 ) === 0;                // an empty object is typecast to 0
( {'2':'3'}|0 ) === 0;         // or a not empty object
( (function(){})|0 ) === 0;    // an empty function is typecast to 0 too
( (function(){ return 3;})|0 ) === 0;

对我来说有一些魔力:

 3 | '0px' === 3;

原文由 Dan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏