简体   繁体   中英

How to set give multiple values to a javascript variable

I'm making a program that requires different parts in a variable the code goes like this

    var num=Math.round(Math.random()*5);
var a;
var a[0]="hi"
/*I've done this before, but remember it as a[num] */
var a[1]...
/*Many vars later*/
console.log(a[num])

this code always says that a[] does not work

You need to tell the compiler it's an array

var a = [];
a[0] = 'hi';
console.log(a[0]); // => hi

Set this

var a;

to

var a = [];

for a declaration of an Array .


Please change this

var num=Math.round(Math.random()*5);

to

var num = Math.floor(Math.random() * 5); // for numbers from 0 to 4

because Math.round rounds depending up or down. Math.floor gets the integer part of a number.


 var num = Math.floor(Math.random() * 5); // for numbers from 0 to 4 var a = []; a[0] = "ha"; a[1] = "he"; a[2] = "hi"; a[3] = "ho"; a[4] = "hu"; document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>'); document.write(a[num]); 

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.

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