The following if-block seems really inefficient. I imagine there is a better way to do this.
This will be used to set parameters in a graphics library. eg camera position, objects position, and others.
Additionally, a generic solution is welcome.
const queryString = window.location.search;
const urlParameter = new URLSearchParams(queryString);
//this code is what my question is about V
if (urlParameter.has("a")) {
a = parseInt(urlParameter.get("a"));
}
if (urlParameter.has("b")) {
b = parseInt(urlParameter.get("b"));
}
if (urlParameter.has("c")) {
c = parseInt(urlParameter.get("c"));
}
if (urlParameter.has("d")) {
d = parseInt(urlParameter.get("d"));
}
//^
Note: I am fairly inexperienced with JavaScript, and mainly use it for hobby projects.
>Solution :
You can use an array with the input parameter names an iterate over it.
But since you cannot assign dynamic variable names in JavaScript, you will need to change your output slightly to use an object:
const allowedParameters = ['a', 'b', 'c', 'd'];
const parsedParameters = {};
allowedParameters.forEach((key)=> {
if (urlParameter.has(key)) {
parsedParameters[key] = parseInt(urlParameter.get(key));
}
});
// To use the values just access each key in the parsedParameters object:
console.log(parsedParameters.a);