1

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;
3
  • Do you want to run all of them, one after the other? Or are there specific cases for running each array? Commented Mar 1, 2013 at 16:50
  • Are you trying to modify the arrays inside the each method, or do you simply need to iterate over them? Commented Mar 1, 2013 at 17:10
  • I need to modify them using split and then append some stuff Commented Mar 1, 2013 at 17:37

1 Answer 1

1

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

1 Comment

Ty, calling window[arrname] = [1,2,3]; from inside the function does not work

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.