Bolehkah anda mengakses pembolehubah tempatan secara dinamik mengikut nama dalam JavaScript?

Patricia Arquette
Lepaskan: 2024-11-14 11:24:02
asal
903 orang telah melayarinya

Can you dynamically access local variables by name in JavaScript?

Dynamically Retrieving Global Variables by Name in JavaScript

The need to access global variables dynamically by their name strings can arise in various scenarios. In JavaScript, global variables are declared outside of any function or block, making them accessible throughout the script.

Accessing Global Variables with Window Object

Traditionally, global variables can be accessed using the window object. For instance, if you have a global variable named someVarName_10 with a value of 20, you can retrieve it using:

window["someVarName_10"] //returns 20
Salin selepas log masuk

Accessing Local Variables Dynamically

However, the question focuses on accessing local variables dynamically by name. In JavaScript, local variables declared within functions or blocks are not accessible outside their scope.

Dynamic Access Only Possible with Global Variables

The solution provided in the answer demonstrates that accessing variables dynamically by name is only possible with global variables. It shows how to use the window object to access a global variable named someVarName_10 and even construct its name dynamically using string concatenation, as in the second code example:

alert(window['someVar' + 'Name_' + num]); //alert 20
Salin selepas log masuk

Update (Edited Question)

The updated question clarifies the intention of accessing local variables. However, as explained earlier, local variables are not accessible outside their scope and cannot be retrieved dynamically by name.

Atas ialah kandungan terperinci Bolehkah anda mengakses pembolehubah tempatan secara dinamik mengikut nama dalam JavaScript?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan