Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use <code>Math.floor()</code> instead of <code>.round()</code> and don't subtract 1 from the length:</p> <pre><code>var randomnumber = Math.floor(Math.random() * imagesarray.length); </code></pre> <p><strong>Edit:</strong> <code>Math.random() * 3</code> will give us numbers between 0 (inclusive) and 3 (exclusive). Using <code>Math.round()</code> the values that result in each number:</p> <pre><code>0: 0.0 — 0.4999 1: 0.5 — 1.4999 2: 1.5 — 2.4999 3: 2.5 — 2.9999 </code></pre> <p>You can see that the high and low numbers each of half the probability of being selected as the numbers in the middle. This is because you will never get numbers in the range <code>-0.5 — -0.9999</code> or <code>3.0 — 3.4999</code> giving these end numbers half the likelihood of being selected.</p> <p><code>Math.floor()</code> eliminates this problem because all the numbers fall within the range. <code>Math.random() * 4</code> will give us numbers between 0 (inclusive) and 4 (exclusive). Using <code>Math.floor()</code> the values that result in each number:</p> <pre><code>0: 0.0 — 0.9999 1: 1.0 — 1.9999 2: 2.0 — 2.9999 3: 3.0 — 3.9999 </code></pre> <p>You may find it useful to use a utility function such as this one:</p> <pre><code>function randomInt(max, min) { min = min || 0; var Max = Math.max(max, min) + 1; var Min = Math.min(max, min); return Math.floor(Math.random() * (Max - Min)) + Min; } </code></pre> <p>The nice thing about this function is that the order of the arguments doesn't matter, and <code>min</code> is optional. Note that, since <code>max</code> is inclusive in this function, you would want to subtract 1 from the array length:</p> <pre><code>var randomnumber = randomInt(imagesarray.length - 1); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload