在 JavaScript 中通过名称字符串动态获取全局变量?

javascriptweb developmentobject oriented programming更新于 2025/8/21 12:28:17

使用 alert(window()) 在 alert 中显示。以下是语法 −

alert(window['yourVariableName' + 'yourVariableName' + otherVariableName]);

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<script>
   var globalVariablelocal_print100=100;
   print100=1;
   alert(window['globalVariable' + 'local_' + print100]);
</script>
</body>
</html>

要运行上述程序,请保存文件名 anyName.html(index.html),然后右键单击该文件并选择在 VS 代码编辑器中使用实时服务器打开选项。

输出


相关文章


有用资源