将字符串与整数连接起来用作 jquery 中的变量(创建动态变量)

concatenate string with integer to use as a variable (creating dynamic variables) in jquery

我有一个长度是动态的数组ARRAY。在下面的示例中,它是 5,但也可能是 10 或 15

ARRAY = [A,B,C,D,E];
var mlength = ARRAY.length;
Using this mlength, how can I create variables. For example  

我想指定为

 mname0=ARRAY[0]; mname1 = ARRAY[1]; mname2= ARRAY[2]; mname3 = ARRAY[3]; mname4 = ARRAY[4];

我试过下面的代码。但这会造成引用错误 Invalid left-hand side in assignment

 for (var i = 0, mlength = ARRAY.length; i < mlength; i++) {
     'mname'+i = ARRAY[i];
 }

如何创建动态变量?

试试这个,

var arr= [];
for(var i =0; i <15; i++) {
  arr.push[{'mname'+i: 'ARRAY'+i}];
}

改为:

var ARRAY = ['A', 'B', 'C', 'D', 'E'];
var mlength = ARRAY.length;


for (var i = 0; i < mlength; i++) {
  console.log('mname' + i + ' = ' + ARRAY[i]);
}

你可以这样做。

var mname;
var ARRAY = ['A','B','C','D','E'];
var mlength = ARRAY.length;
for(var i=0;i<mlength;i++){
   window['mname'+i]=ARRAY[i];
}
console.log(mname1);

所以这可能对您有所帮助。在此代码中,我将所有变量设为 window 对象成员,因为 Window 是全局对象。

这个答案来自 this question 我是作者。但是我不觉得这个问题本身是重复的。


创建动态变量名,这里有3个选项。

eval(不推荐)

你可以使用Javascript函数eval来实现你想要的。但是请注意,不推荐(我强调了两次,希望您能理解!)。

Don't use eval needlessly!

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

它会像这样使用:

eval('var mname' + i + ' = "something";');

Window object notation(优于eval,仍然不推荐)

此方法包括在全局 window 对象上使用 JavaScript 提供的对象表示法。这污染了全局 window 范围,并且可以被其他不好的 JS 文件覆盖。如果您想了解更多关于该主题的信息,这是一个很好的问题:Storing a variable in the JavaScript 'window' object is a proper way to use that object?.

要使用该方法,您需要这样做:

window['mname' + i] = something;
alert(window[varName]);

使用对象(推荐)

最好的解决方案是创建您自己的变量范围。例如,您可以在全局范围内创建一个变量并为其分配一个对象。然后,您可以使用对象表示法来创建动态变量。它的工作方式与 window 相同:

var globalScope = {};

function awesome(){
    var localScope = {};
    globalScope['mname' + i] = 'something';
    localScope['mname' + i] = 'else';

    notSoAwesome();
}

function notSoAwesome(){
    alert(globalScope['mname' + i]); // 'something';
    alert(localScope['mname' + i]); // undefined
}

全局范围内的变量也可以被视为window对象的成员:

var mname,ARRAY = ["A","B","C","D","E"];
var mlength = ARRAY.length;
for(var i=0;i<mlength;i++){
    window["mname"+i]=ARRAY[i];
}
alert(mname0);

但您应该考虑直接使用 ARRAY

这是我生成数组

的 link
$(document).ready(function (e){  
     var cars = ["Saab", "Volvo", "BMW"];
     var text=''; 
     var mname="name";

     for (i = 0; i < cars.length; i++) { 
        text += mname+i+'='+cars[i]+',';
     }
     alert(text);
});

根据您的要求,您的增量值将动态生成字符串。 希望对您有所帮助。