0

I want to pass a string for an array's name to a function, and the function create that array, e.g:

make_array('array_name', data);

function make_array(array_name, data){
    array_name = [];

    // do stuff

    array_name.push(//stuff);

}

I don't want to have to create the array first manually

rpsep2
  • 3,061
  • 10
  • 39
  • 52
  • do you want your array variables injected in global scope? I might sugest you creating a namespace for your arrays. So you can do something like this in your global namespace: var arrayNamespace = {}; and in your function you'll do: arrayNamespace[arrayName] = []; arrayNamespace[arrayName].push(value); – eAbi Jun 11 '14 at 10:22

3 Answers3

2

You can do .

window[array_name] = [];
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

You can use eval() to do it.

eval("var " + array_name + " = []");
jbduzan
  • 1,106
  • 1
  • 14
  • 30
0

If you just want the function to return an array, there is no need to create it beforehand. You can just do this:

function make_array(data){
    var array_name = [];

    // do stuff

    array_name.push(//stuff);
    return array_name;
}

var my_new_array = make_array(data);
neelsg
  • 4,802
  • 5
  • 34
  • 58