简体   繁体   English

如何在javascript中使用变量定义变量?

[英]How can i define a variable with a variable in javascript?

EDIT 2 : This is my first post on stock overflow and although I sometimes have some bad, questions to ask.编辑 2 :这是我关于库存溢出的第一篇文章,虽然我有时会提出一些不好的问题。 i thought id at least fix the formatting considering I can not delete this.考虑到我无法删除它,我认为 id 至少可以修复格式。

I essentially wanted to automate variable creation , although at the time I did not not such things as arrays existed surprisingly.我本质上想自动化变量创建,尽管当时我并没有出人意料地存在数组之类的东西。

I want to automate the creation of this variable我想自动创建这个变量

var l = createSprite(200,200);

I want to be able to define one variable , with another like this :我希望能够定义一个变量,另一个是这样的:

var count = 5;
var l + count = 1;
count++;
var l + count = 2;
var l=30 
var l + "foo" = 40`

if I were to run this, lfoo would be returned undefined.如果我要运行它,lfoo 将返回 undefined。 Why?为什么? Is this impossible?这是不可能的吗? If so how can i automate defining variables?如果是这样,我如何自动定义变量?

You could take an object and use l as part of the key for the access.您可以获取一个对象并使用l作为访问密钥的一部分。

 var l = 30 , object = { [l + "foo"]: 40 }; console.log(object[l + "foo"]); console.log(object);

You can't define variables like this.你不能像这样定义变量。 You have to define it through writing the absolute name for them.您必须通过为它们编写绝对名称来定义它。 But to call them you can use window["l"+"foo"].但是要调用它们,您可以使用 window["l"+"foo"]。

 var l = 40; var lfoo = 30; console.log(window["l"]+"...."+window["l"+"foo"]);

You could use window to declare global variables您可以使用 window 来声明全局变量

var str = 'l' + 'foo';
window[str] = 40;
//Then you can access lfoo directly

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM