0

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 tried var currentArray = ("regionArray"+number)[]; but that doesn't seem to be the right way either.

0

5 Answers 5

5

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]; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

No need for the object keys overhead - an array of array is good enough.
2

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];

}

1 Comment

I got a lot of great answers, but I'm picking this one because not only is it a correct answer but he also noticed that I said that the number variable would be 1 or 2. ;)
2
function region(i) {
    var regionArray = [
        [1093, 1276, 436, 541],
        [563, 747, 310, 423, 744, 947, 601, 715]
    ];

    var currentArray = regionArray[i];
}

Comments

0

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];

Comments

0

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 ]; 
}

1 Comment

This is syntactically invalid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.