What is the JavaScript >>> operator and how do you use it?

后端 未结 7 2233
野性不改
野性不改 2020-11-22 02:41

I was looking at code from Mozilla that add a filter method to Array and it had a line of code that confused me.

var len = this.length >>> 0;
         


        
7条回答
  •  感动是毒
    2020-11-22 03:16

    The unsigned right shift operator is used in the all the array extra's method implementations of Mozilla, to ensure that the length property is a unsigned 32-bit integer.

    The length property of array objects is described in the specification as:

    Every Array object has a length property whose value is always a nonnegative integer less than 232.

    This operator is the shortest way to achieve it, internally array methods use the ToUint32 operation, but that method is not accessible and exist on the specification for implementation purposes.

    The Mozilla array extras implementations try to be ECMAScript 5 compliant, look at the description of the Array.prototype.indexOf method (§ 15.4.4.14):

    1. Let O be the result of calling ToObject passing the this value 
       as the argument.
    2. Let lenValue be the result of calling the [[Get]] internal method of O with 
       the argument "length".
    3. Let len be ToUint32(lenValue).
    ....
    

    As you can see, they just want to reproduce the behavior of the ToUint32 method to comply with the ES5 spec on an ES3 implementation, and as I said before, the unsigned right shift operator is the easiest way.

提交回复
热议问题