I need help figuring out how to create an array in JavaScript or TypeScript that contains a list of environment names. I want to iterate over this array and use the values as variable names within a closure.
My initial attempt looks like this (even though I know it won't work):
const envs = [ dev, test, uat, stage, prod ]
for i = 1; i < envs.length; i++ {
const envs[i] = `prefix${envs[i]}`;
}
I have come across using eval as a solution:
let k = 'value';
let i = 0;
for i = 1; i < 5; i++ {
eval('var ' + k + i + '= ' + i + ';');
}
This would result in:
console.log("value1=" + value1); // value1=1
console.log("value2=" + value2); // value2=2
console.log("value3=" + value3); // value3=3
console.log("value4=" + value4); // value4=4
Is there an alternative method that does not involve using eval? I prefer to avoid eval because our code scanner flags it as a potential risk, resulting in constant explanations for false positives.
Edit
To provide further clarification: I am aiming to create a variable that can be referenced later in my code. While the console.log
examples showcase the values, I prioritize the ability to reference the name in subsequent code such as
newThing(envs[i] + i, other, params)
.
Additionally, I am steering away from utilizing items like window
and document
due to variations depending on where the code is executed.