[英]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 这段代码总是说a []不起作用
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 . 用于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.round
向上或向下取Math.round
。 Math.floor
gets the integer part of a number. Math.floor
获取数字的整数部分。
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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.