What array.length >>> 0; is used for?

Possible duplicates:
1. What good does a zero-shift bit shift of 0 do? (a β†’> 0)
2. JavaScript is three times more

I dug through some MooTools code and noticed that this fragment is used in every array method:

var length = this.length >>> 0; 

What is the use of this? It does not seem to me that this is some kind of max length, like 3247823748372 >>> 0 === 828472596 and 3247823748373 >>> 0 === 828472597 (so that both of them are 1 higher if it would be better for maxLength to do that something like var length = Math.min(this.length, MAX_LENGTH) ?).

+4
source share
2 answers

>>> - bitwise operator "zero filling right shift" .

JavaScript numbers can represent both integers and floating point numbers. Sometimes you only need an integer. Any positive JavaScript number representing a number less than 2 ^ 32 will be rounded (truncated, as in Math.floor ) to the nearest integer. Numbers β‰₯ 2 ^ 32 are rotated by 0. A number less than 0 will turn into a positive value (thanks to the magic of representing two additions).

However, this.length supposed to ALWAYS be an integer less than 2 ^ 32 ... so I cannot explain why the code will do this. The result should be the same as this.length .

+1
source

This is apparently the safest way to ensure that the length is a non-negative (32-bit) integer.

Another example of where JavaScript does not have the appropriate standard functions, this time to save converting unknown types to unsigned 32-bit integers.

+2
source

Source: https://habr.com/ru/post/1383311/


All Articles