mardi 15 septembre 2015

Don't understand this use of bitwise "or" operator in JavaScript

I was reading the article on the 'this' keyword on JavaScriptIsSexy here when I reached the first of the listed cases when the behavior of 'this' can cause problems, where the sample code is as follows:

    var user = {
      data:[
        {name:"T. Woods", age:37},
        {name:"P. Mickelson", age:43}
      ],
      clickHandler:function (event) {
      var randomNum = ((Math.random () * 2 | 0) + 1) - 1; 
​

        console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
      }
    }
​

    $ ("button").click (user.clickHandler); 

This will serve as a good illustration of the object-dependence of 'this', and I understand that principle, but I'm quite hung up on something that seems like it should be simple:

var randomNum = ((Math.random () * 2 | 0) + 1) - 1; 

This is intended to generate an integer, right? I see what I believe is the bitwise OR operator "|" in there, but I don't understand what it's doing there. Multiply the product of Math.random by 2 or 0? How is that determined?




Aucun commentaire:

Enregistrer un commentaire