-1

I tried the following code, but yet it didn't work:

<html>
<body>
<p id="demo"></p>
<p id="demo2"></p>

<script>

var max=1000;
var text=new Array();
var i=0;

for (i; i<=max ; i++) {
    text[i]=i;
}
var newx0=new Array();
newx0.push(text);
var rand = newx0[Math.floor(Math.random() * newx0.length)];
var randomx0=newx0[Math.floor(Math.random()* newx0.length)];
document.getElementById("demo").innerHTML = rand;
document.getElementById("demo2").innerHTML = newx0;

The proglem is the rand valuable prints 0 to 1000 just like the newx0 valuable

myname
  • 29
  • 2
  • 9

2 Answers2

4

new0 is an array, which contains one element: your other text array. That means newx0.length is always 1. Why are you doing that array wrapper anyways? Why not just have

var rand = text[Math.floor(Math.random() * text.length)];
           ^^^^                            ^^^^

instead?

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • and is it possible that: now i have 0 to 1000...and i also need more 4x time...so i have to an array with number 0 to 1000 and 5 times...example 0,....1000, 0, ....,1000 so on? – myname Dec 04 '14 at 15:00
0
/**
 * Returns a random integer between min (inclusive) and max (inclusive)
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var array = [wherever your array comes from];     //Set up your array to be sampled
var randIndex = getRandomInt(0, array.length());  //Randomly select an index within the array's range
var randSelectedObj = array[randIndex];           //Access the element in the array at the selected index

getRandomInt was taken from here: Generating random whole numbers in JavaScript in a specific range?

Community
  • 1
  • 1
Aaron Averett
  • 896
  • 10
  • 12