简体   繁体   中英

How to use multiple strings in a single JS variable call

I'm trying to do this:

variable[playernumber][arrayposition] = thisvalue;

Should I instead be thinking of "variable" as an array object which itself contains an array? Perhaps something like:

variable[playernumber].subvariable[arrayposition]

Note: Number of players is theoretically infinite, so I can't use a switch.

What you're trying to do works. Consider the code below:

var array = [[]]; //declare array in array

array[0][0] = 'hello';

alert(array[0][0]); //<-- prints hello

Either approach is reasonable. However, if the first approach you suggested, which would be a two-dimension array, is sufficient for you needs, then that is the simpler approach. You could declare it like so:

var variable = [];

Then add arrays of values to that array like so, assuming playernumber is a variable with an integer value:

var someValues = [8, 17, -6, 34];
variable[playernumber] = someValues;

Then this line would show the number -6 in an alert box:

alert(variable[playernumber][2]);

By the way variable is a terrible name for a variable. Please don't actually use that.

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