简体   繁体   English

Javascript中来自数组的随机对象

[英]Random objects from Arrays in Javascript

A query regarding arrays in JavaScript: // colors only works when quoted, reason? 有关JavaScript中数组的查询:// 颜色仅在引用时才起作用,原因? 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. 我得到这样的数组,并且需要将以下颜色数组中的随机值传递给我的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'); 

That's an array of string literals that contain numbers. 那是一个包含数字的字符串文字数组。

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

That's an array of number literals. 那是数字文字的数组。

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

That's an array of string literals. 那是一个字符串文字数组。

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

That's an array of variables. 那是一个变量数组。

The numbers will be automatically stringified when concatenated with the " : " string and therefore work like number strings, but your variables will just throw Undefined Variable exceptions. 数字与" : "字符串连接时将自动进行字符串化,因此其工作方式类似于数字字符串,但是您的变量只会抛出Undefined Variable异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM