0

如何使用javascript在具有动态键和动态值的数组中创建动态数组?

例如,请查看以下我想要的内容:

Studentslist  
  Student Info 1
      "name" => "varun",
      "age" => "24"

  Student Info 2
      "name" => "Kumar",
      "age" => "25"

添加有关此问题的更多信息

我有一个像这样的单选按钮

<input type="radio" value="student1" id="student1" name="student1group1"/>
<input type="radio" value="student2" id="student1" name="student1group1"/>

<input type="radio" value="student3" id="student2" name="student1group2"/>
<input type="radio" value="student4" id="student2" name="student1group2"/>

当单击任何单选按钮时,我需要在数组中设置一个数组,例如在单击student1group12 个单选按钮中的任何一个时,我需要获取如下所示的数组

Studentslist  
  Student Info 1
          "name" => clicked value of the radio button,
4

2 回答 2

1

试试这个

var Studentslist = [{name:"varun",age:"24"}, {name:"Kumar",age:"25"}]

alert(Studentslist.length)  //=>2

alert(Studentslist[0].name)  //=>varun

alert(Studentslist[1].age)  //=>25

Studentslist.push({name:"nickname",age:"30"})  //=>
//[{ name="varun", age="24"},{ name="Kumar", age="25"},{ name="nickname", age="30"}]

使用 JQuery 进行动态处理(每次单击复选框后更改数据)

var Studentslist = new Array();

$(function(){
    $("input[type='radio']").click(function(){
      if ($(this).is(":checked")) {          
        Studentslist[$(this).attr('name')] = {value:$(this).attr('value'), id:$(this).attr('id')}
      }
    })
})

//console.log (Studentslist['student1group1']) //=>   { value="student1", id="student1"}
//console.log (Studentslist['student1group2']) //=>   { value="student3", id="student3"}
于 2012-09-11T06:48:48.940 回答
0

你可以试试这个

var Studentslist  = [];

var student = {name:"varun", age:24 }

Studentslist.push(student);

student = {name:"Kumar", age:25};

Studentslist.push(student);

student = {name:"Varun Kumar", age:26}

Studentslist.push(student);

要获取学生详细信息,您可以尝试。

for(var x in Studentslist)
{
    alert(x.name);
}

使用单选按钮,您可以尝试

<input type="radio" value="student1" id="student1" name="student1group1"/>
<input type="radio" value="student2" id="student1" name="student1group1"/>

<input type="radio" value="student3" id="student2" name="student1group2"/>
<input type="radio" value="student4" id="student2" name="student1group2"/>

javascript:

var Studentslist  = [];

window.onload = function(){
    var allinputs = document.getElementsByTagName("input");
    for(var x in allinputs)
    {
       if(x.type == "radio")
       {
          x.onclick = function() {
             if(this.checked){
               var student = {name: x.value };
               Studentslist.push(student);
             }
          }
       }
    }
}

您可以调用此方法进行警报。

function CheckStudentDetails
{
    for(var x =0;x<Studentslist.length; x++)
    {
        for(var y in Studentslist[x])
        {
             alert(Studentslist[x][y]);
        }
    }

}
于 2012-09-11T06:53:05.870 回答