Home  >  Article  >  Web Front-end  >  Some uncommon and practical functions in javascript

Some uncommon and practical functions in javascript

巴扎黑
巴扎黑Original
2016-12-19 15:30:481227browse

1. ~indexOf()

Generally speaking, to determine whether a string contains a substring, you can use indexOf(subString) > -1 to express

We can also use ~indexOf(subString) to express

IndexOf() returns -1 to indicate absence, returns 0 and a number greater than 0 to indicate existence~ The result of -1 is 0, which is equivalent to false in if

0 and greater than 0 are numbers that are not 0 after the ~ operation. Equivalent to true in if

2. ~~

Two consecutive bitwise inversions can remove the decimal places and retain integers. In the positive range, it is equivalent to Math.floor and in the negative range, it is equivalent to Math.ceil

Similar operations include n<<0 n>>0 n|0

Of course, there is a limitation in using these algorithms for rounding, that is, the digital range can only be used within the 32-bit binary number range. That is to say, the number should be between -2147483648 ~ 2147483647, which is also a number of plus or minus more than 2 billion. Under normal circumstances, there is no problem.

3. This is a problem and makes me a little confused.

The toFixed method It is to round Number to a number with specified decimal places

The Math.round method can round the number to the nearest integer

But for -4.5.toFixed(0) and Math.round(-4.5), it returns a -5, one returns -4


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
Previous article:JS ad jumpNext article:JS ad jump