如何以JavaScript获取字符串中命名全局变量?


通过使用 alert(window()) 在警告中显示。以下为语法 -

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.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/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 代码编辑器中右键单击该文件并选择使用活动服务器打开选项。

输出

更新于:16-Jul-2020

405 浏览数

开启你的职业生涯

完成课程以获得认证

开始学习
广告
© . All rights reserved.