简体   繁体   中英

Can data added in javascript arrays be accessed later?

I am new to Javascript, is there a way to store data in an array and be able to access it later. Example :

I have created an array

  • If I click on my HTML file button (add a question), a function generates a random Id for a question block (like id="13819").
  • It is then added to an array of question Id's
  • Once the function is done running, does the Id stay in the array once added? Or does the array reset when the function called again?
  • If it does reset, how do you make it to not reset?

It depends on where your variable is created. If it is a top level variable(global) you will be able to add new data during the whole users session. On the other side if that variable is created inside a function it will be erased every time you call that function.

Short answer: Yes

Long answer: It depends

It depends on where you created the array. This is known as the scope of the array.

If it is inside the function, the scope of the array is inside the function, so only things inside the function can access the array. Once the function is finished, the array no longer exists.

You can create it in the global scope, ie as an attribute of the global window object, but you should try as much as possible to limit the scope of your variables, so that you don't pollute the global namespace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM