Search code examples
javascriptdynamicstrong-typingloose-typing

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.


Solution

  • 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];
    …