Home >Web Front-end >JS Tutorial >Tips for using bitwise not (~) in JS
This time I will bring you the tips for using bitwise not (~) in JS. What are the precautions for using bitwise not (~) in JS? . The following is a practical case. Let’s take a look. take a look.
Bitwise NOTOperator is represented by a tilde (~), and the result of executing bitwise NOT is the complement of the returned value
Now let me look at a few examples
Example 1
console.log(4); console.log(~4); console.log(~~4);
Example 2
console.log(4.9.toString(2)); console.log(~4.9); console.log(~~4.9);
Example 3
console.log(-4.1.toString(2)); console.log(~-4.1); console.log(~~-4.1);
Through the above example we can know that for integers,bitwise negation isThe negative value of the operand is subtracted by 1.
But it is more troublesome for floating point numbers. When operating floating point numbers, the decimal part will be directly discarded, and then the negative value is subtracted by 1
Using this, we can use ~~ instead of Math.floor();
For example, we often ask for a The midpoint of array can be directly ~~(arr.length/2). Is it more convenient than Math.floor()?
In addition, the |0 operation can also achieve similar effects to ~~, such as (arr.length/2)|0
Another little knowledge:
console.log(~~NaN);//0console.log(NaN|0);//0
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Custom validator for Reactive Form
Request cross-domain solution CORS
The above is the detailed content of Tips for using bitwise not (~) in JS. For more information, please follow other related articles on the PHP Chinese website!