0

I am searching through existing data in Js through a variable, I found that maybe I can access the data through window["variable_name"] , but Js can't find the variable.

How am I going to access the data, or is there a better way to store the data and access it.

The data format

let info1=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}, ...];
let info2=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}, ...];
.
.
.
let info2000=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}, ...];

Trying to access the variable

for (let i=1; i<=2000; i++) {
    console.log(window["info"+i]);
}
henry Chan
  • 59
  • 7
  • Are the variables being sought in global scope? Can you change their declaration to use `var` instead of `let`? In short, what constraints does a solution need to meet? I answered a similar question [here](https://stackoverflow.com/a/50111572/5217142) but is has limitations: - using `eval` is never attractive and may be disabled in some run time environments. – traktor Feb 12 '23 at 08:57

1 Answers1

2

You cant access the variable with window because you declared the variable with let. You need to use var to declare.

Variables declared by let are only available inside the block where they're defined. Variables declared by var are available throughout the function in which they're declared.

var info1=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}];
var info2=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}];

console.log(window["info1"]);
console.log(window["info2"]);
Joshua Ooi
  • 1,139
  • 7
  • 18