通过JavaScript中的名称字符串动态获取全局变量 [英] Get global variable dynamically by name string in JavaScript

查看:583
本文介绍了通过JavaScript中的名称字符串动态获取全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<script>
//in one script
var someVarName_10 = 20;
</script>

我希望通过变量名称从另一个脚本访问此变量。使用window对象很简单,是否可以使用局部变量?

I want to get access to this variable from another script by name of variable. With window object its simple, is it possible with local variable?

我的意思是通过以下代码访问此var:

I mean access this var by code like this:

<script>
  alert(all_vars['someVar' + 'Name' + num]);
</script>


推荐答案

你想做这样的事吗?

<script>
//in one script
var someVarName_10 = 20;

alert(window["someVarName_10"]); //alert 20

</script>

更新:因为OP编辑了这个问题。

Update: because OP edited the question.

<script>
  num=10;
  alert(window['someVar' + 'Name_' + num]); //alert 20
</script>

这篇关于通过JavaScript中的名称字符串动态获取全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆