2014-12-04 162 views
-1

我嘗試下面的代碼,但仍然沒有奏效:
如何從數組中選擇一個隨機項目?

<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; 

的proglem是蘭特有價值打印0到1000就像newx0寶貴

+4

你可以整理你的代碼(即關閉標籤等所以它的完成),並解釋什麼並不瞭解它的工作? – 2014-12-04 14:48:42

+1

什麼不起作用? – renatoargh 2014-12-04 14:49:32

+0

'text'已經是一個數組了,但是你將該數組推入另一個數組'newx0' - 這是故意的嗎? – Jamiec 2014-12-04 14:49:58

回答

4

new0是一個數組,其中包含一個元素:您的其他text陣列。這意味着newx0.length總是1。爲什麼你要做這個數組包裝呢?爲什麼不只是有

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

取而代之?

+0

是的,這就是我需要的,thx *。*但爲什麼問題與newx0? – myname 2014-12-04 14:58:53

+0

是否有可能:現在我有0到1000 ...而且我還需要更多4倍的時間...所以我必須有一個數組0到1000和5次...示例0,.... 1000,0,...,1000等等? – myname 2014-12-04 15:00:44

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從這裏拍攝: Generating random whole numbers in JavaScript in a specific range?

相關問題