Javascript 使用变量名和字符串动态生成数组

Javascript 使用变量名和字符串动态生成数组,javascript,jquery,arrays,Javascript,Jquery,Arrays,我正在使用一组数组填充页面上的一些单选项 //holds the set value of the variable var universalVariables = [thing1, thing2, thing3]; //used for the classes in the radios to get values later var universalNames = ['thing1','thing2','thing3']; //used to put a label on each

我正在使用一组数组填充页面上的一些单选项

//holds the set value of the variable
var universalVariables = [thing1, thing2, thing3]; 
//used for the classes in the radios to get values later
var universalNames = ['thing1','thing2','thing3']; 
//used to put a label on each radio
var universalAttributes = ['THING ONE', 'THING TWO', 'THING THREE']; 
其次是:

$.each(universalVariables, function(index, val) {
  $('#universalAttributes').append('<br />' + universalAttributes[index] + '<br /><div class="radio"><label><input type="radio" name="' + universalNames[index] + '" value="false">FALSE</label></div><div class="radio"><label><input type="radio" name="' + universalNames[index] + '" value="true">TRUE</label></div>')
});

//set data
$.each(universalVariables, function(index, val) {
  if (universalVariables[index] == false) {
    $("input[name=" + universalNames[index] + "][value=false]").prop('checked', true);
  } else if (universalVariables[index] == true) {
    $("input[name=" + universalNames[index] + "][value=true]").prop('checked', true);
  }
});
$。每个(通用变量、函数(索引、val){
$(“#universalAttributes”).append(“
”+universalAttributes[index]+”
false true) }); //设置数据 $.each(通用变量、函数(索引、val){ if(universalVariables[索引]==false){ $(“输入[name=“+universalNames[index]+”][value=false]”)prop('checked',true); }else if(universalVariables[索引]==真){ $(“输入[name=“+universalNames[index]+”][value=true]”)prop('checked',true); } });
这会创建三个(因为我的数组中有三个变量)收音机,但显然可以处理任意数量的收音机。您所需要做的就是在阵列中提供信息(而不是编码收音机选择自己)

这里的三条信息

当您必须添加变量时,问题就出现了。理想情况下,我希望生成前两个数组。我可以提供单词列表,然后生成。诀窍(对我来说)是这样做的,一个数组有字符串名,另一个需要变量名而不是变量值

必须有一个简单的方法来做到这一点。接受任何建议。

您可以将变量的“元数据”存储在对象中,并通过与变量名称匹配的键访问它们,如下所示:

您还可以在将输入附加到容器的同时设置checked属性,这样就不需要第二个循环

var通用变量={
“事情1”:{
价值观:正确,
属性:“第一件事”
},
“事情2”:{
值:false,
属性:“第二件事”
},
“事情3”:{
价值观:正确,
属性:“第三件事”
},
};
//这样我们就可以保证正确的顺序
var universalNames=['thing1'、'thing2'、'thing3'];
$.each(通用名称、函数(索引、名称){
var objVar=通用变量[名称];
$(“#全球贡献”)
.append(“
”+objVar.attribute+ “
假真” });


@不要用坏标签。编辑!还有为什么要使用3个变量,1就可以了,只需将一个新对象推到它上面<代码>var universal=[];universal.push({variable:thing1,name:'thing1',attribute:'thingone'})
然后在每个变量中,您不需要索引引用其他变量。@lawrencerone然后我需要对每个变量进行push。不知道这会有什么帮助。@jonmrich看一下我的解决方案,看看这是否就是你想要的。