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

1
  • 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); Commented Jun 11, 2014 at 10:22

3 Answers 3

2

You can do .

window[array_name] = [];
Sign up to request clarification or add additional context in comments.

Comments

0

You can use eval() to do it.

eval("var " + array_name + " = []");

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.