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]);
}
1
  • 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 but is has limitations: - using eval is never attractive and may be disabled in some run time environments. Commented Feb 12, 2023 at 8:57

1 Answer 1

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"]);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.