Reverse retrieval in javascript and reverse retrieval ~~ Meaningless _ javascript tips-js tutorial

Source: Internet
Author: User
Operator ~, It means bitwise inversion. On the surface ~~ It doesn't make sense. Here is a good example. You can refer to the following operators ~, It means bitwise inversion. On the surface ~~ It doesn't make sense. In fact, you can convert a floating point number into an integer in JS.

The Code is as follows:



Script
Var myArray = new Array ();
MyArray. push ("");
MyArray. push ("B ");
MyArray. push ("c ");
MyArray. push ("d ");

// Now we need to randomly retrieve an element from the array.
Var random = myArray [~~ (Math. random () * myArray. length)]; // Math. random () returns a pseudo-random number between 0 and 1, which may be 0, but always less than 1)

Var I = 7.94;
I = ~~ I;
Alert (I );

Var j = 7.34;
J = ~~ J;
Alert (j );

Script



As shown above, if no ~~, The random result is a decimal number, which is to remove the decimal number and retain the integer. For example, I = 7, j = 7. However, this mechanism does not exist in C. In C, float cannot be reversed by bit, and forced type conversion can be used in C (whereas in JS, this mechanism is not available, floating Point to integer) to achieve the same purpose (discard the fractional part, retain the integer part ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.