简体   繁体   中英

How does | and + do the trick to turn string into number?

When I was reading a doc about Symbol on MDN, I noticed these things can trun string into number which I've never seen before.

Quote:

When trying to convert a symbol to a number, a TypeError will be thrown (eg +sym or sym | 0).

For example:

+"15"

will return

15

which is number type.

Also

"15" | 0

can do the same thing.

I am wondering how does this trick work. Can you help?

+"15" is casting the "15" to a number type, the same way -15 works.

eg.

>> -"15" === -15
>> true

The second case, "15" | 0 "15" | 0 is doing the same thing, casting to an integer in order to perform a Bitwise OR .

Which means taking the bits of 15 and ORing them with the bits of zero.

15 in binary is, for example 00001111 and zero is 00000000 so each bit is or'd with each other resulting in 15 again which is returned.

Unary Plus Operator

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_()

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

+"6";//6
+6;//6
+-6;//-6
+undefined;//NaN
+false;//0
+true;//1
+null;//0
+{};//NaN
+[];//0
+function(){};//NaN

Bitwise OR Operator

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#.7c_%28Bitwise_OR%29

The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). Numbers with more than 32 bits get their most significant bits discarded. Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. The operator is applied to each pair of bits, and the result is constructed bitwise.

The Bitwise OR Operator first converts both operands to 32-bit integers and each bit is compared. When comparing the two bits, if any of the bits is 1, 1 is returned. If both bits are 0, 0 is returned.

Example:

2|1;//produces 3
--------
00000010   //2 in binary
00000001   //1 in binary
--------
00000011   //3 in binary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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