I can access a variable easily:
function accessVariable(accessFunction, variable) {
var namespaces = accessFunction.split(".");
for (var b = 0; b < namespaces.length; b++) {
if (namespaces[b] != "") {
try {
variable = variable[namespaces[b]];
} catch {
variable = undefined;
};
};
return variable;
};
But updating this gotten variable is something that I don't know how to do.
It's easiest if you use a separate function to update. This can take the new value as another argument.
Then you stop the iteration before the last item in namespace, and use that as the index to assign to.
function updateVariable(accessFunction, variable, value) {
var namespaces = accessFunction.split(".");
for (var b = 0; b < namespaces.length - 1; b++) {
if (namespaces[b] != "") {
try {
variable = variable[namespaces[b]];
} catch {
variable = undefined;
}
}
}
if (variable) {
variable[namespaces.pop()] = value;
}
}
let obj = {a: {b:[{c: 10}]}};
updateVariable('a.b.0.c', obj, 20);
console.log(obj);
Define a single global-scoped variable, and put your variables there.
var Glob = {}; // globally scoped object
function changeVar(){
Glob.variable1 = 'value1';
}
function SeeVar(){
alert(Glob.variable1); // shows 'value1'
}