I have an array, for example:
argumentsArray = ["arg1", "arg2"];
And I have a function:
function1 = function () {
console.log(arg1);
console.log(arg2);
};
Now of course executing function1 will throw an error because arg1 and arg2 aren't defined. But I don't want to define these, I want them used as arguments, like so:
function1 = function (arg1, arg2) {
console.log(arg1);
console.log(arg2);
};
Now we could execute function1 when we pass two arguments to it:
function1("string1", "string2");
// will log "string1" and "string2"
But the problem is, I can't change the source code of function1. I can't edit it's arguments. I'm aware of the bind() and apply() function, but they would do the wrong thing, because the actually apply the strings:
getFunction1WithArgumentsFromArray = function () {
return function () {
return function1.apply(this, argumentsArray);
};
};
getFunction1WithArgumentsFromArray();
// would return function1("arg1", "arg2");
The thing is, arg1 and arg2 are not defined yet. They aren't strings or any other thing yet. My code looks something like this:
function1 = function () {
console.log(arg1);
console.log(arg2);
};
argumentsArray = ["arg1", "arg2"];
defineArgs = function() {
arg1 = "hey";
arg2 = "hello";
};
getFunction1WithArgumentsFromArray = function (argumentsArray) {
argumentsToUse = convertArrayOfStringsToArrayOfVariables(argumentsArray);
// HOW???
return function () {
return function1(argumentsToUse[0], argumentsToUse[1]);
};
// or what should i put here???
};
getFunction1WithArgumentsFromArray();
// should return this:
// function1 = function(arg1, arg2) {
// console.log(arg1);
// console.log(arg2);
// };
// without executing it.
So what I'm really looking for is a function that turns an array of strings into an array of variables with the names of these strings:
["arg1", "arg2"] --> [arg1, arg2]
But making this directly would be a problem, because JavaScript then searches for these variables. As I said, these variables aren't defined...
One I idea I had is to use apply() and pass an Array with eval("string")s like so:
getFunction1WithArgumentsFromArray = function () {
return function () {
return function1.apply(
this,
[eval(argumentsArray[0]), eval(argumentsArray[1])]
);
};
};
getFunction1WithArgumentsFromArray();
// would return "arg1 is not defined", because eval() executes the function as I define it
This may seem very very unnecessary to you, but as I already said, I can't change the function1 so I have to create it's arguments list in another function. I mean, of course I can change it, but the project I'm working on, uses an array to get arguments.
function1is trying to work with variables which flat-out aren't defined, it's arguably wrong. How'd you get into this particular predicament…?evalorwindow[varname]. Basically, you need to structure your code. If you want to have named values you can access using their name as a string, then use objects and properties.