dotty dotty - 7 months ago 45
Javascript Question

Generate unique random numbers between 1 and 100

How can I generate 8, say, unique random numbers between 1 and 100 using JavaScript?

Answer

var arr = []
while(arr.length < 8){
  var randomnumber=Math.ceil(Math.random()*100)
  var found=false;
  for(var i=0;i<arr.length;i++){
	if(arr[i]==randomnumber){found=true;break}
  }
  if(!found)arr[arr.length]=randomnumber;
}
document.write(arr);

Comments