user2065483
user2065483

Reputation: 1225

Loading arrays dynamically into a jQuery function

Okay guys,

I need some help with this jQuery dilemma:

I have 3 arrays declared globally in the header of my website:

var array1 = [];
var array2 = [];
var array3 = [];

I have a function like this:

function setDropDownList(raw_id){
    jQuery.each(mytest, function(key, value) {
      var mytest = value.split('|');
    }
}

Instead of "mytest" I need to dynamically load each of the 3 arrays declared globally above.

How can I do it?

I'm thinking of something lime this:

function setDropDownList(raw_id, "??? how can I generate which array I need: array1 or 2 or 3?"){
    jQuery.each(the_needed_array, function(key, value) {
      var the_needed_array = value.split('|');
    }
}

In PHP, there is something called variable variables, and I could have something like this.

var array_name = 'array1';

And in the function:

$$array_name;

Upvotes: 1

Views: 121

Answers (1)

David Fregoli
David Fregoli

Reputation: 3407

Supposing those are global variables, you need to operate on the window object, using the array notation if you have

var arrname = 'array1'
window[arrname] = [1,2,3]; // window.arrname won't work but this will

then

console.log(window.array1)

will yield

[1,2,3]

if they are not global variables you can use this instead of window to target whatever is the container object (this will actually reference window if you're in the global scope).

var myobj = {
  myfunc : function() {
    var an = 'iamanarray';
    this[an] = [1,2,3];
    console.log(this[an]);            // [1,2,3]
    console.log(this.an);             // undefined
    console.log(this['iamanarray']);  // [1,2,3]
    console.log(myobj.iamanarray);    // [1,2,3]
    console.log(iamanarray);          // reference error
    console.log(window.iamanarray);   // reference error
  }
}

Upvotes: 1

Related Questions