0
    var temp = "<div class='cell' style='width:{width}px; height: {height}px; background-image: url(i/photo/{index}.jpg)'></div>";
    var w = 1, html = '', limitItem = 49;
    for (var i = 0; i < limitItem; ++i) {
        w = 200 +  200 * Math.random() << 0;
        html += temp.replace(/\{height\}/g, 200).replace(/\{width\}/g, w).replace("{index}", i + 1);
    }
    $("#freewall").html(html);

I'm not really good in Javascript bitwise operation especially the left shift operator (the <<). Can anyone explain to me why the developer uses that with Math.random() times 200 and plus 200 for the width? The code is excerpt from freewall.js example codes.

user3856437
  • 2,071
  • 4
  • 22
  • 27

1 Answers1

0

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

So, the author wants it to be somewhere between 200 and 400px wide. PX need to be integers, so the author then uses the left shift of a 0 to truncate right of the decimal. See https://stackoverflow.com/a/12125432/5314386 for more about the truncation.

Community
  • 1
  • 1