What does a single vertical bar mean in JavaScript?

大城市里の小女人 提交于 2019-11-27 02:16:17

问题


What does this expression mean in JS?

Value |= this.value

回答1:


It's binary "OR", just like in C or C++ or Java. In this case, it's used in its assignment operator form, so

value |= this.value

means that this.value and value are both converted to 32-bit integers, and a bitwise OR operation is performed. If value were 10 and this.value were 3 before the operation (that is, 01010 and 011 in binary) the result would be 11 (01011 in binary).

The binary logic operators in Javascript are notable in Javascript because the work is carried out on integer values.

The term "bit-wise" is perhaps more accurate than "binary". The operations act on each bit of a numeric value, specifically the numeric values coerced to signed 32-bit integers. The result is also a signed 32-bit integer (according to the spec).

However, JavaScript numbers "at rest" are always 64-bit binary floating point values. Thus the results of bitwise operators, though computed with 32-bit integer math, are stored in floating point form. That works because the range of 32-bit integers fits comfortably and precisely in a 64-bit float.




回答2:


This will perform a bitwise OR between the bits in this.value and the bits already stored in Value, then store the result back into Value.

var Value = 42;  // 00101010
Value |= 96;     // 01100000
window.alert(Value);  // 01101010 -> 106



回答3:


As others have pointed out, this is the bitwise OR operator. However, I don't think people use it much on numerical values in Javascript as - generally - you don't do a lot of computation in Javascript. To give you a better idea why this operator is useful, consider the far more common scenario that the user needs to fill in at least one of multiple textfields.

Say you have this HTML:

<input type="text" class="phone-nr" id="home-phone-nr-1" />
<input type="text" class="phone-nr" id="home-phone-nr-2" />
<input type="text" class="phone-nr" id="home-phone-nr-3" />
<input type="text" class="phone-nr" id="mobile-phone-nr-1" />
<input type="text" class="phone-nr" id="mobile-phone-nr-2" />
<input type="text" class="phone-nr" id="mobile-phone-nr-3" />

The user has the option to fill in multiple phone numbers, but will have to supply at least one.

The easiest way to do this (with jQuery in this case) is:

var valid = false;
$('.phone-nr').each(function(i, item){
  valid |= $(item).val();
}); // untested code

valid will be true if at least one input field with class phone-nrhas a non-empty value.

If every field must be filled in (a more common requirement) you can do it like this with the bitwise AND operator:

var valid = true;
$('.phone-nr').each(function(i, item){
  valid &= $(item).val();
}); // untested code

valid will only be true if all input fields have a value.

If at least single field is required to be filled in, but no more than one you can use the XOR operator:

var valid = false;
$('.phone-nr').each(function(i, item){
  valid ^= $(item).val();
}); // untested code

Those are, in my opinion, the real-world uses of bitwise operators in Javascript.




回答4:


Some practical use for that operator I have found:

( 3|0 ) === 3;             // целые числа не изменяет
( 3.3|0 ) === 3;           // у дробных чисел отбрасывает дробную часть
( 3.8|0 ) === 3;           // не округляет, а именно отбрасывает дробную часть
( -3.3|0 ) === -3;         // в том числе и у отрицательных дробных чисел
( -3.8|0 ) === -3;         // у которых Math.floor(-3.3) == Math.floor(-3.8) == -4
( "3"|0 ) === 3;           // строки с числами преобразуются к целым числам
( "3.8"|0 ) === 3;         // при этом опять же отбрасывается дробная часть
( "-3.8"|0 ) === -3;       // в том числе и у отрицательных дробных чисел
( NaN|0 ) === 0;           // NaN приводится к нулю
( Infinity|0 ) === 0;      // приведение к нулю происходит и с бесконечностью,
( -Infinity|0 ) === 0;     // и с минус бесконечностью,
( null|0 ) === 0;          // и с null,
( (void 0)|0 ) === 0;      // и с undefined,
( []|0 ) === 0;            // и с пустым массивом,
( [3]|0 ) === 3;           // но массив с одним числом приводится к числу,
( [-3.8]|0 ) === -3;       // в том числе с отбрасыванием дробной части,
( [" -3.8 "]|0 ) === -3;   // и в том числе с извлечением чисел из строк,
( [-3.8, 22]|0 ) === 0     // но массив с несколькими числами вновь зануляется
( {}|0 ) === 0;                // к нулю также приводится пустой объект
( {'2':'3'}|0 ) === 0;         // или не пустой
( (function(){})|0 ) === 0;    // к нулю также приводится пустая функция
( (function(){ return 3;})|0 ) === 0;

and some magic for me:

3 | '0px' === 3;



回答5:


It's a bitwise or assignment operator, similar to +=. If you run a test on it like this:

<ol>
<script language="javascript">
var x=false;
document.writeln("<li>"+x+"</li>");
x|=true;
document.writeln("<li>"+x+"</li>");
x&=false;
document.writeln("<li>"+x+"</li>");
</script>
</ol>

You'll get this output (in IE)

1.false
2.1
3.0

Essentially, x|=y is the same as saying x=x|y



来源:https://stackoverflow.com/questions/4024429/what-does-a-single-vertical-bar-mean-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!