0

I want to create an array from a function. How would I go about doing this so that the array name is passed within the parameter.

function arrayCreate(name){
     name = [];
    }

So if I used arrayCreate("Hello") I would have Hello = [] as an array. The obvious problem is I'm passing a string so how would I overcome this.

To explain a bit more about my problem I have a function which updates a chart as seen below:

      self.updateChart = function(name){

        if (typeof chartData == 'undefined') {
          chartData = [];
        }
        chartData.push({
          date: game.tickCount,
          visits: self.price,
        });
        priceLabour.validateData();
        return chartData;
        }

Now the "chartData = []" and "priceLabour" I would like for it to be dynamic and change based on the "name" parameter.

9
  • 1
    even if you get it, what do you do with the named array? Commented Feb 20, 2017 at 16:21
  • I want to display different charts which require different named arrays Commented Feb 20, 2017 at 16:23
  • and how do you hand over the data? Commented Feb 20, 2017 at 16:25
  • I have an Object called Market.list which to create a graph I use Market.list[4].updateChart();. Obviously it's fine for one market but I want to re-use the code Commented Feb 20, 2017 at 16:27
  • It doesn't look like it should matter what the array is named since it's only being referenced inside this function. Why do you need to specify a name? Commented Feb 20, 2017 at 16:29

2 Answers 2

1

You can't just create variables by a string. You can create, assign, and read properties on objects using a string:

var obj = {};
obj[name] = [];
obj[name].push(...);
Sign up to request clarification or add additional context in comments.

3 Comments

So there's no way I can change the edited code I just added?
@epayne not that i can tell. seems to be a leaky global however.
I declared chartData = []; outside the function
0

You can create a dynamically named array as a property of an object. Not entirely sure what your needs are but here's an example based on your provided code.

  var data = {};

  self.updateChart = function(name){
    // Store a shallow clone of the chartData array in the data obj
    data[name] = chartData.slice(0);

    if (typeof data[name] == 'undefined') {
      data[name] = [];
    }
    data[name].push({
      date: game.tickCount,
      visits: self.price,
    });
    priceLabour.validateData();
    return data[name];
  };

After calling updateChart you should be able to use data["myString"] elsewhere to refer to your array.

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.