I have value an array like this:
multi_arr = ["resi_spec","resi_desc"];
So each array value is considered as a variable and I want to store some value of these variables dynamically like this:
resi_spec = "good morning"
resi_desc = "good evening";
So that the array values are converted as variables. Is this possible?
I don't want use use obj[resi_spec] like this and i used array not variable if i just enter resi_spec means , i'll get good morning.
You could use an object to hold the values:
var multi_arr = ["resi_spec","resi_desc"];
var resi = {};
multi_arr.forEach(function(val) {
resi[val] = "good morning";
});
Obviously you will want to set different values for each object attribute which you could accomplish with a helper function:
var lookupHelper = function(key) {
if (key == 'resi_spec') return 'good morning';
if (key == 'resi_desc') return 'good evening';
};
var multi_arr = ["resi_spec","resi_desc"];
var resi = {};
multi_arr.forEach(function(val) {
resi[val] = lookupHelper(val);
});
You could also do the following.. Although not really recommended, since you will be creating global variables. Jsfiddle
var varNames = ["name1", "name2", "name3"];
for(var i = 0; i < varNames.length; i++){
window[varNames[i]] = i;
}
console.log(name1); // 0
console.log(name2); // 1
console.log(name3); // 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With