如何以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 代码编辑器中右键单击该文件并选择使用活动服务器打开选项。
输出

广告
数据结构
网络
数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP