Grant
Grant

Reputation: 11376

Dynamic Javascript - Is This Valid?

can someone tell me if this is valid javascript? I know you couldnt do this sort of thing in c# but js is a much looser language..

var arrayToUse = "arr" + sender.value;
for (i = 0; i <= arrayToUse.length; i++) {
    // something..
}

specifically - the dynamic generation of the array name..

update..

so i have an array called arrMyArray which is initialised on document ready. sender.value = "MyArray" - but could be something else eg MyArray2

I want to dyanimcally iterate over the array that is indicated by the sender.value value.

Upvotes: 0

Views: 116

Answers (3)

Zach
Zach

Reputation: 7940

What you need to do is access a variable with the name "arr" + sender.value. Accessing the variable whose contents are "arr + sender.value doesn't do what you want -- that's just a string.

To access the variable with that name, you can look it up as a global (globals are members of the window object in the browser):

window["arr" + sender.value]

This is safer and faster than using eval() because it doesn't run code in a JavaScript execution context to evaluate the string -- it just looks up a variable in the window object with that name.

Upvotes: 1

Jeremy Banks
Jeremy Banks

Reputation: 129836

To get a variable name defined by a variable, you need to use eval, like so:

var arrayToUse = eval("arr" + sender.value);

However, you must be very careful with this, because controlling sender.value would allow someone to hijack your entire application this way. You should usually try to find another solution.

If the variable is defined at the globally, you can look it up as window["arr" + sender.value] instead. This is still not ideal, but is less of a security risk.

Upvotes: 1

David Wolever
David Wolever

Reputation: 154664

Yes, this is entirely valid.

arrayToUse will be a string (regardless of the value of sender.value — it will be converted to a string), and i will iterate from 0 to the string's length).

One minor note: it should be for (**var** i = 0; …), otherwise i will be treated as a global variable, which will almost certainly end badly if you've got multiple loops running at the same time.

Edit: you want to get the array based on the name? In that case you've got to look it up in whatever context the array is defined.

If it's a global array, use window.

For example:

var arrayName = "arr" + sender.value;
var array = window[arrayName];
…

Upvotes: 6

Related Questions