在JS中使用string作为变量名? [英] Using string as variable name in JS?

查看:122
本文介绍了在JS中使用string作为变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使后续代码生效?

var x = 'name';

然后,使用x中的值,因为它是一个变量,然后设置它,所以如果我想让它成为NAME,我会得到结果:

and then, to use the value inside x, as it was a variable, and set it, so that if i want it to be NAME, i'll have the result:

var name = 'NAME';

有可能吗?

推荐答案

不直接,没有。但是,您可以分配到窗口,它将其指定为全局可访问的变量:

Not directly, no. But, you can assign to window, which assigns it as a globally accessible variable :

var name = 'abc';
window[name] = 'something';
alert(abc);

然而,一个更好的解决方案是使用你自己的对象来处理这个问题:

However, a much better solution is to use your own object to handle this:

var name = 'abc';
var my_object = {};
my_object[name] = 'something';
alert(my_object[name]);

这篇关于在JS中使用string作为变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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