Home >Web Front-end >JS Tutorial >Negating and negating again in javascript is meaningless_javascript skills

Negating and negating again in javascript is meaningless_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:53:151304browse

Operator~ means bitwise negation. On the surface, ~~ (reverse and then negate) is meaningless. In fact, floating point numbers can be turned into integers in JS.

Copy code The code is as follows:


<script> <br>var myArray = new Array(); <br>myArray.push("a"); <br>myArray.push("b"); <br>myArray.push("c"); <br>myArray .push("d"); <br><br>//Now we need to randomly take out an element from the array<br>var random = myArray[~~(Math.random()*myArray.length)]; // Math.random() returns a pseudo-random number between 0 and 1, which may be 0 but is always less than 1, [0,1) <br><br>var i = 7.94; <br>i = ~~i ; <br>alert(i); <br><br>var j = 7.34; <br>j = ~~j; <br>alert(j); <br><br></script>



As above, if there is no ~~, then the decimal is randomly obtained, and the decimal part of the decimal is removed, leaving the integer. As above i=7, j=7. However, this mechanism does not exist in C. A floating point number (float) cannot be bitwise inverted in C, and forced type conversion can be used in C (but there is no such mechanism in JS. Floating point numbers are converted to integers. ) achieves the same purpose (discarding the decimal part and retaining the integer part).
Negating and negating again in javascript is meaningless_javascript skills
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