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

后端 未结 7 2068
野性不改
野性不改 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:35

    Driis has sufficiently explained what the operator is and what it does. Here's the meaning behind it/why it was used:

    Shifting any direction by 0 does returns the original number and will cast null to 0. It seems that the example code that you are looking at is using this.length >>> 0 to ensure that len is numeric even if this.length is not defined.

    For many people, bitwise operations are unclear (and Douglas Crockford/jslint suggests against using such things). It doesn't mean that its wrong to do, but more favorable and familiar methods exist to make code more readable. A more clear way to ensure that len is 0 is either of the following two methods.

    // Cast this.length to a number
    var len = +this.length;
    

    or

    // Cast this.length to a number, or use 0 if this.length is
    // NaN/undefined (evaluates to false)
    var len = +this.length || 0; 
    
    0 讨论(0)
提交回复
热议问题