如何从数组动态创建javascript变量?

vsaztqbk  于 2022-12-28  发布在  Java
关注(0)|答案(3)|浏览(124)

假设我有一个变量名数组:

var varNames = new Array("name1","name2","name3");

如何通过循环varNames数组来创建var name1var name2var name3

bqjvbblv

bqjvbblv1#

这将创建全局变量(在全局名称空间中,即window)。

var varNames = ["name1","name2","name3"];
for (var i=0;i<varNames.length;i+=1){
  window[varNames[i]] = 0;
}
name1; //=> 0

因为使用全局变量被认为是不好的做法,所以您可以在custum对象中创建变量:

var myVariables = {}
   ,varNames = ["name1","name2","name3"];
for (var i=0;i<varNames.length;i+=1){
  myVariables[varNames[i]] = 0;
}
myVariables.name1; //=> 0

[ES20xx]

const myVariables = ['name1', 'name2', 'name3']
  .reduce( (a, v, i) => ({...a, [v]: i + 1 }), {});

console.log(JSON.stringify(myVariables, null, 2));

// to 'global' variables
Object.entries(myVariables).forEach( ([key, value]) =>
  window[key] = value );
  
console.log(`name1: ${name1}, name2: ${name2}`);
xqkwcwgp

xqkwcwgp2#

你可以这样做。我添加了警报来证明你可以为那些变量设置一个值。

var varNames = new Array("name1","name2","name3");
for(var i = 0; i < varNames.length; i++) {
    window[varNames[i]] = i;
}
alert("name1: " + name1);
alert("name2: " + name2);
alert("name3: " + name3);
zlwx9yxi

zlwx9yxi3#

对您的问题的直接回答是-您可以使用eval来完成此操作:

var varNames = new Array("name1","name2","name3");

for (var i=0; i<varNames.length; i++) {
    var varName = varNames[i];
    eval("var "+varName); // would be "var name1"
}

请注意,虽然这被认为是不好的做法,通常没有理由使用eval的这种情况。还请注意,它更常见的是创建数组使用以下样式:

var varNames = ["name1", "name2", "name3"];

相关问题