Home  >  Article  >  Web Front-end  >  Tips for using bitwise not (~) in JS

Tips for using bitwise not (~) in JS

php中世界最好的语言
php中世界最好的语言Original
2018-03-19 16:45:062306browse

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 NOT

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);

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn