以编程方式声明变量? [英] Declare variables programmatically?

查看:103
本文介绍了以编程方式声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一堆这样的变量:

I am trying to create a bunch of variables like this:

function l(){
    var a1 = 2,
        a2 = 4,
        a3 = 6,
        a4 = 8,
          .
          .
        a20 = 40;
}

但这需要太多行,我正在寻找一种方法做得更聪明。这就是我的想法:

But this is taking too many lines, and I am searching for a way to do it smarter. This is what I have come up:

function l(){
    for(var i=0; i<20; i++){
        var ("a"+i) = 2*i;
    }
}

但它可能无效,如果它有效(它没有),变量仍然在范围内范围内。任何想法?

But it probably won't work, and if it works (it does not) the variables will still be inside the for scope. Any ideas?

window["a"+i] or eval(...)

这些不起作用,因为我不希望它们在全局范围内。

These don't work because I don't want them to be in the global scope.

通常一个数组会很好,但我我只是在试验这是否可以在JavaScript中使用。也许在将来我会遇到这样的事情。

Usually an Array would be fine, but I am just experimenting if this is possible in JavaScript. Maybe in the future I would encounter something like this.

推荐答案

不要这样做。做。不。做。这个。 使用数组。

Don't do this. Do. Not. Do. This. Use an array.

考虑到您正在创建创建的麻烦他们以编程方式,你认为你如何以编程方式引用

Given the trouble you're having creating them programmatically, how do you think you'd refer to them programmatically?

这篇关于以编程方式声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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