A query regarding arrays in JavaScript: // 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.
<!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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.