JavaScript Array & Global Variable Reference

76 Views Asked by At

I am trying to reference a global variable's value using my array output but I am unsure how to do that. I want to make these references outside the function as I will need to create many functions that use these variables.

Ignore the PFGetValue part, I need to use that for the program I am coding in. There will be many more dd_meg_x but this is just to show you what I'm doing. Currently, this will return the correct the text "dd_meg_x" - but I want to then reference the variable defined above. So for example, if the result in the array is dd_meg_1, I want the output to be "M Energy 16"

var dd_meg_1 = "M Energy 16";
var dd_meg_2 = "Ulra Energy";
var dd_meg_3 = "Another Option Here";

function canOrderMeg1() {
  var brand = "meg";
  var arrayLength = 21;
  var canArray = [];
  var variableName;

  for (i = 0; i <= arrayLength; i++) {
    variableName = ("dd_" + brand + "_" + i);
    if (PFGetValue(variableName) === "Y") {
        canArray.push(variableName);
    }
    canArray.join(", ");
  }
  return canArray[0];
}

function canOrderMeg2() {
  var brand = "meg";
  var arrayLength = 21;
  var canArray = [];
  var variableName;

  for (i = 0; i <= arrayLength; i++) {
    variableName = ("dd_" + brand + "_" + i);
    if (PFGetValue(variableName) === "Y") {
        canArray.push(variableName);
    }
    canArray.join(", ");
  }
  return canArray[1];
}
2

There are 2 best solutions below

0
On

Try this:

var dd_meg_1 = "M Energy 16";
var dd_meg_2 = "Ulra Energy";
var dd_meg_3 = "Another Option Here";

function canOrderMeg1() {
  return ["dd_meg_1", "dd_meg_2", "dd_meg_3"];
}

for(let i = 0; i < canOrderMeg1().length; i++){
  if(typeof canOrderMeg1()[i] !== "undefined") {
    console.log(window[canOrderMeg1()[i]]);
  }
}

0
On

Try

return eval('string output code');

So this would look like

return eval(array output);