Javascript 基于计数结果创建动态变量名

Javascript 基于计数结果创建动态变量名,javascript,jquery,variables,Javascript,Jquery,Variables,我试图将字符串和数字组合成一个动态生成的变量。 目前正以这种方式尝试: const ElementCount = 2; for (i = 1, i <= ElementCount, i++) { let SampleVariable[i] = "test"; } 我的代码似乎错了-我必须在这里更改什么? 解决方案也可以是原生JS或jQuery 非常感谢 代码中几乎没有错误 您可以使用逗号,分隔语句。你应该使用分号 您正在for循环内部声明SampleVariable,因此它在外

我试图将字符串和数字组合成一个动态生成的变量。 目前正以这种方式尝试:

const ElementCount = 2;

for (i = 1, i <= ElementCount, i++) {
    let SampleVariable[i] = "test";
}
我的代码似乎错了-我必须在这里更改什么? 解决方案也可以是原生JS或jQuery


非常感谢

代码中几乎没有错误

  • 您可以使用逗号
    分隔语句。你应该使用分号
  • 您正在for循环内部声明
    SampleVariable
    ,因此它在外部不可用。在循环之外声明它
  • 你不应该使用自变量,因为它们只是相差1。您应该将它们存储在数组中,并使用
    SampleVariable[number]
    访问它们
  • 您应该初始化
    i=0
    ,否则
    SampleVariable
    的第一个元素将是
    未定义的
  • const ElementCount=2;
    让SampleVariable=[];
    for(设i=0;iconsole.log(SampleVariable)解决方案是使用
    eval
    ,但这是一种讨厌的代码,避免使用“eval”,只需使用
    数组
    对象

    1、
    eval
    解决方案:

    const ElementCount = 2;
    
    for (let i = 1; i <= ElementCount; i++) {
        eval("let SampleVariable[" + i + "] = 'test'");
    }
    
    3、
    对象
    解决方案:

    const ElementCount = 2;
    let Variables = []
    for (let i = 1; i <= ElementCount; i++) {
        Variables["SampleVariable" + i] = "test";
    }
    
    const ElementCount = 2;
    let Variables = {}
    for (let i = 1; i <= ElementCount; i++) {
        Variables["SampleVariable" + i] = "test";
    }
    
    const ElementCount=2;
    让变量={}
    对于(设i=1;i这是我的解

    const ElementCount = 2;
    
    for(i = 1; i <= ElementCount; i++) {
        this['SampleVariable'+i] = "test";
    }
    SampleVariable1 // "test" (browser)
    this.SampleVariable2 // "test"
    
    const ElementCount=2;
    
    对于(i=1;我输入的范围在外部未知。
    SampleVariable1
    是数组的元素还是自变量?@MaheerAli:是independent@NinaScholz:要点很好!如何在此功能之外使其可用?JS不允许您以您尝试的方式动态确定变量的名称。如果语句或
    开关
    ,或最有用的数组或对象来保存不同的值。到目前为止,我最喜欢数组解决方案,尽管我不太熟悉其用法。通过数组声明后,如何访问例如“SampleVariable1”,以便我可以使用其值?使用
    变量[“SampleVariable1”]
    要获取值,您的“数组解决方案”实际上没有使用数组,因为您使用的是字符串键而不是数字索引。它实际上与“对象解决方案”相同“除
    变量外,
    可以访问标准数组属性/方法,因为您没有在数字索引位置为其指定任何元素,因此无法正常工作。要真正使用数组,您必须将其指定给
    变量[i]
    而不是
    变量[“SampleVariable”+i]
    在我看来,新变量在我的声明函数之外是不可用的。“SampleVariable1未定义”是用于“eval”解决方案的吗?(我强烈建议不要使用数组或对象。)看起来@tony.ga在这里犯了一个错误,一个解决方案是用
    var
    替换
    let
    ,这很有效,但我不喜欢在知道它引用全局对象时间接使用
    This
    。如果你真的想这样做,只需使用
    window['SampleVariable'+I]
    const ElementCount = 2;
    
    for(i = 1; i <= ElementCount; i++) {
        this['SampleVariable'+i] = "test";
    }
    SampleVariable1 // "test" (browser)
    this.SampleVariable2 // "test"