动态Javascript数组

时间:2012-09-11 06:44:26

标签: javascript

如何使用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"/>

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

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

2 个答案:

答案 0 :(得分: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"}

答案 1 :(得分: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]);
        }
    }

}