Reputation: 17
I want to concatenate a string passed as argument with another word and then use it as a variable name for an array. Is this allowed?
function getFromSomewhere(arg1) {
string newName = arg1 + "sampleWord";
var (use NewName here) = [];
}
Upvotes: 0
Views: 82
Reputation: 30242
You can add the variable to the window object:
function getFromSomewhere(arg1) {
var newName = arg1 + "sampleWord";
window[newName] = [];
}
getFromSomewhere("blip");
console.log(blipsampleWord); // You'd get []
Upvotes: 1
Reputation: 26161
There is no way you can add new variables to the function definition after the function is defined.. However you can always add new properties to the function object defined or it's prototype and you can access them as follows;
function getFromSomewhere(arg1) {
var newName = arg1 + "_sampleWord_";
this.getFromSomewhere.varName = newName + "test";
this.getFromSomewhere.prototype.varName = newName + "best";
console.log(this.getFromSomewhere.varName);
console.log(this.getFromSomewhere.prototype.varName);
}
getFromSomewhere("test");
Upvotes: 1
Reputation: 902
You can use newName
as the name of a property
function getFromSomewhere(arg1) {
var myVariableNamedAtRuntime = [];
string newName = arg1 + "sampleWord";
myVariableNamedAtRuntime[newName] = [];
}
and then access the array as ...
myVariableNamedAtRuntime[newName]
Upvotes: 1
Reputation: 138257
Yes it is possible. But no, you dont want to do that. Dynamic variable names are always a sign, that you should use an object instead. In this case i think you could simply map your array of strings to an array of objects:
function namesToObj(arr){
return arr.map( name => ({
name,
price:10
}));
}
namesToObj(["banana","tomato"])
/*results in
[{name:"banana",price:10},{name:"tomato",price:10}]
*/
Upvotes: 0
Reputation: 386560
You could use an object with the wanted fruits as key for the array, like in the example.
The object is easy to access and to maintain.
var array = ["apple", "banana", "grapes"],
prices = {};
array.forEach(function (k) {
prices[k] = [];
});
prices.apple.push(1, 10, 3);
console.log(prices.apple[2]);
console.log(prices);
Upvotes: 1
Reputation: 655
Not allowed, unfortunately. Variable names, such as newName, that we see are rid of at compilation time for optimization. Your machine will have no use for it's name newName during runtime, which is when you're trying to assign the name to it.
Upvotes: 1