I want to create a local variable dynamically. JavaScript: Dynamically Creating Variables for Loops is not exactly what I am looking for. I dont want an array. I want to access
Here is working sample based on Chris Baker answer: Function scope (using arguments)
function myFn() {
function keyList(params) {
var str = '';
for (var key in params) {
if (params.hasOwnProperty(key)) {
str += ',' + key;
}
}
return str.length ? str.substring(1) : str;
}
function valueList(params) {
var list = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
list.push(params[key]);
}
}
return list;
}
var params = {
'var1': 'value1',
'var2': 'value2'
};
var expr = 'document.write("Inside the function : " + var1 + "
")'
var fn;
eval('var fn = function(' + keyList(params) + '){' + expr + '};');
fn(valueList(params));
}
myFn();