2013-08-27 17 views
0

有關JavaScript中的數組的查詢: // 顏色只有在引用時才起作用,原因?我得到這樣一個數組,並且需要將隨機顏色數組中的隨機值傳遞給我的URL,但它不起作用。使用Javascript的數組中的隨機對象

<!DOCTYPE html> 
<html> 
<body> 

<p id="demo">Click the button to display a random number.</p> 

<button onclick="myFunction()">Try it</button> 

<script> 
function myFunction() 
{ 

//**num** works both ways, even when they are quoted or if I use the commented line. 
var num = new Array('1','2','3','4','5','6','7','6'); 
//var num = new Array(1,2,3,4,5,6,7,6); 

//**colors** only works when quoted, reason? I am getting an Array like this and need to pass the random values from following colors array to my URL, but it doesn't work. 

var colors= new Array('red','blue','green','orange','cyan','yellow', 'black'); 
//var colors= new Array(red,blue,green,orange,cyan,yellow, black); 

var item = num [Math.floor(Math.random()*num .length)]; 
var item2= colors[Math.floor(Math.random()*colors.length)]; 


document.getElementById("demo").innerHTML=item +" : "+ item2; 
} 
</script> 

</body> 
</html> 
+0

因爲數字將轉換爲字符串,但字符串不能表示爲數字。沒有引號,它們不是字符串文字,而是變量名稱,並且會失敗。 – Bergi

+0

你是什麼意思的「我得到這樣一個數組」? – Bergi

+0

我得到一個數組作爲顏色(紅色,藍色,綠色,黑色) 所以它不起作用 –

回答

0
var num = new Array('1','2','3','4','5','6','7','6'); 

這是包含數字的字符串文字的數組。

var num = new Array(1,2,3,4,5,6,7,6); 

這是數字面值的陣列。

var colors= new Array('red','blue','green','orange','cyan','yellow', 'black'); 

這串文字的數組。

var colors= new Array(red,blue,green,orange,cyan,yellow, black); 

這是一個變量數組。

這些數字在與" : "字符串連接時會自動字符串化,因此像數字字符串一樣工作,但您的變量僅會拋出Undefined Variable例外。

+0

這是什麼修復? –