Setting variable by string name in javascript?
<pre><code>//window["Fluent"]["Include"]

function setGlobalVariableByName(name,value)
{
    var indexes = name.split(".");
    var variable = null;
    $.each(indexes, function()
    {
        if (variable == null){
            variable = window[this];
        }else{
            variable = variable[this];
        }
    });

    variable = value;
}

setGlobalVariableByName("Fluent.Include.JqueryPulse",true);
console.log(Fluent.Include.JqueryPulse) // prints false
</code></pre>

<p>this doesn't work, obviously. It would work if I just wanted to get the variable's value, but not for setting it.</p>

<pre><code>window["Fluent"]["Include"]["JqueryPulse"] = true;
console.log(Fluent.Include.JqueryPulse) // prints true
</code></pre>

<p>how could I achieve something like this without using eval?<br>
I'd need some way to programmatically add array indices to this, I'd guess</p>

<hr>

<p>The following works, can you suggest a better way to code it in order to make it more DRY?</p>

<pre><code>function setGlobalVariableByName(name,value)
{
    var indices = name.split(".");
    var parent;
    $.each(indices, function(i)
    {
        if(i==indices.length-1){
            if (!parent){
                window[this] = value;
            }else{
                parent[this] = value;
            }
        }else if (!parent){
            parent = window[this];
        }else{
            parent = variable[this];
        }
    });
}
</code></pre>

<hr>

<pre><code>setGlobalVariableByName : function(name, value)
{
    var indices = name.split(".");
    var last = indices.pop();
    var parent;
    $.each(indices, function(i)
    {
        if (!parent){
            parent = window[this];
        }else{
            parent = variable[this];
        }
    }); 
    if (!parent){
        window[last] = value;
    }else{
        parent[last] = value;
    }
}
</code></pre>
