我读过'what are bitwise operators?',所以我知道 bitwise operators是什么,但我仍然不清楚如何使用它们。有没有人能提供一些真实的例子,说明位运算符在JavaScript中的用处?
谢谢。
编辑:
深入研究一下,我发现有几个地方使用了按位运算符,例如:(只有&运算符)
// 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;
发布于 2009-03-17 12:52:28
示例:
解析十六进制值以获取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
发布于 2013-03-28 01:00:58
我在生产脚本中大量使用位运算符进行数值转换,因为有时它们比Math
或parseInt
等效运算符快得多。
我要付出的代价是代码可读性。因此,我通常在开发中使用Math
,在生产中使用位。
You can find some performance tricks on jsperf.com。
正如你所看到的,浏览器多年来不会优化Math.ceil
和parseInt
,所以我预测按位将是in furure as well更快更短的方式。
奖励:适用于| 0
的cheat sheet:一种简单快速地将任何内容转换为整数的方法:
( 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;
发布于 2010-02-09 03:36:48
在JavaScript中,可以使用双位否定(~~n
)替换Math.floor(n)
(如果n
是正数)或parseInt(n, 10)
(即使n
是负数)。n|n
和n&n
始终产生与~~n
相同的结果。
var n = Math.PI;
n; // 3.141592653589793
Math.floor(n); // 3
parseInt(n, 10); // 3
~~n; // 3
n|n; // 3
n&n; // 3
// ~~n works as a replacement for parseInt() with negative numbers…
~~(-n); // -3
(-n)|(-n); // -3
(-n)&(-n); // -3
parseInt(-n, 10); // -3
// …although it doesn’t replace Math.floor() for negative numbers
Math.floor(-n); // -4
单次按位求反(~
)计算-(parseInt(n, 10) + 1)
,因此两次按位求反将返回-(-(parseInt(n, 10) + 1) + 1)
。
更新:更准确的基准测试在这里:
https://stackoverflow.com/questions/654057
复制相似问题