vendredi 6 décembre 2019

JavaScript: Finding a variable's value by its name, is eval acceptable here?

I have an array of variables I want to be "watching out" for. That is: if they were previously defined in the code, I need to be able operate on their values.

var a = 'foo'; // only a gets defined

// ...more code here... IMPORTANT: I can only control what comes BELOW this line!

var target = 'exmple.com/?';
var gets = ['a', 'b', 'c']; // these are the names of the variables I want to check for

gets.forEach(function(element) { // checking each one
   if(typeof element !== 'undefined') { // if it's previously defined
  target += "&"+element+"="+eval(element); // add `&a=foo` to target
}
});

alert(target);

I'd like the alert to be printing example.com/?&a=foo

I've seen the tons of other answers not to use the eval function, and I have tried window[element] in place without success. How would it be best to do this without having to write an if/else for every variable I want to check?





Aucun commentaire:

Enregistrer un commentaire