-1

How would I access a variable if I have its name stored in a string?

let test1 = 6;
let test2 = 4;

function findVar(index) {
  let result = "test" + index;
  console.log(result);
}

findVar(1);
findVar(2);

Running this just prints 'test1' and 'test2' as strings, how can I access their values?

  • Put them in an Object: `let variables = {test1: 6, test2: 4};` Then use bracket notation to access them: `console.log(variables[result]);` – mykaf Jan 13 '23 at 20:09

1 Answers1

0

// default / window context
var test1 = 6;
var test2 = 4;

// sub / object context
var context2 = {
  subProp1 : 10
  }

// find var using key of object /context
// because 'everything' is an Object...
// we can reference properties / attributes using the key
function findVar( prefix, index, context ) {
  return context[ prefix + index ];
}

console.log( findVar( 'test', 1, this ) ); // outputs 6
console.log( findVar( 'test', 2, this ) ); // outputs 4

console.log( findVar( 'subProp', 1, context2 ) ); // outputs 10
This Guy
  • 495
  • 4
  • 9
  • change the scoping declaration from 'let' to 'var', for window context. this was an issue on the original code – This Guy Jan 13 '23 at 20:23