[英]Random objects from Arrays in Javascript
有關JavaScript中數組的查詢:// 顏色僅在引用時才起作用,原因? 我得到這樣的數組,並且需要將以下顏色數組中的隨機值傳遞給我的URL,但這是行不通的。
<!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>
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
異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.