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>
因爲數字將轉換爲字符串,但字符串不能表示爲數字。沒有引號,它們不是字符串文字,而是變量名稱,並且會失敗。 – Bergi
你是什麼意思的「我得到這樣一個數組」? – Bergi
我得到一個數組作爲顏色(紅色,藍色,綠色,黑色) 所以它不起作用 –