anon anon - 1 year ago 87
Javascript Question

random number WITH duplicates

This current code gives me

(input value) numbers, all lower then
and drops the data off at
in a random order -- which is fine; but I would like for the numbers to be completely random, as it stands it gives me one of every number lower/including
(so no duplicates, just a random order counting up to

How would I write it so I would get duplicates?

<!DOCTYPE html>

<input id="input1" type="number" min=10" max="100" onchange="test();">

<p id="demo"></p>

function test() {
var N = document.getElementById("input1").value;
var arr = [];
while(arr.length < N){
var randomnumber = Math.ceil(Math.random()*N);
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
document.getElementById("demo").innerHTML = arr;}


Answer Source

to specifically answer your question:


if(arr.indexOf(randomnumber) > -1) continue;

that is a conditional clause which checks for duplicates (in your code)

edit2: also check the .innerHTML assignment - i may give you [Object object] or [Array array]

edit: can I ask how this was elusive?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download