I want to create an array called currentArray
, but I want its contents to be made up from a different array. Basically a copy. However, I want to affect which array is being copied into currentArray
with a variable (int).
Here's what I mean:
function region(number)
{
var regionArray1 = [1093, 1276, 436, 541];
var regionArray2 = [563, 747, 310, 423, 744, 947, 601, 715];
var currentArray = (regionArray+number)[];
}
number
will be either 1 or 2. What is the correct way to do this, if I can? I've also 开发者_JAVA百科tried var currentArray = ("regionArray"+number)[];
but that doesn't seem to be the right way either.
The "best" way would be to make regionArray
an array of arrays (or an Object of arrays):
function region(number)
{
var regionArray = {
"1": [1093, 1276, 436, 541],
"2": [563, 747, 310, 423, 744, 947, 601, 715]
};
var currentArray = regionArray[number];
}
I would use a two dimensional array:
function region(number) {
var regionArrays = [
[1093, 1276, 436, 541],
[563, 747, 310, 423, 744, 947, 601, 715]
];
var currentArray = regionArrays[number - 1];
}
function region(i) {
var regionArray = [
[1093, 1276, 436, 541],
[563, 747, 310, 423, 744, 947, 601, 715]
];
var currentArray = regionArray[i];
}
You should use a switch/case. eval
should not be used in cases where you know all the information that needs to be executed.
function region(n) {
// define arrays ...
switch(n) {
case 1 : currentArray = regionArray1; break;
case 2 : currentArray = regionArray3; break;
}
}
If this extends to more than 2 you can have an array of arrays and simply assign currentArray = arrayChoices[n];
why not this :
function region(number)
{
var regionArray = [];
regionArray[0] = [1093, 1276, 436, 541];
regionArray[1] = [563, 747, 310, 423, 744, 947, 601, 715];
var currentArray = regionArray[ number ];
}
精彩评论