如何遍历javascript数组变量

时间:2013-08-14 18:18:54

标签: javascript jquery

我有一个如下的数组

countries: [{
      "name": "Afghanistan",
      "cca2": "AF",
      "calling-code": "93"
    },
    //{"name":"Åland Islands","cca2":"AX","calling-code":"358"},
    {
      "name": "Albania",
      "cca2": "AL",
      "calling-code": "355"
    }, {
      "name": "Algeria",
      "cca2": "DZ",
      "calling-code": "213"
    }, {
      "name": "American Samoa",
      "cca2": "AS",
      "calling-code": "1684"
    }, {
      "name": "Andorra",
      "cca2": "AD",
      "calling-code": "376"
    }, {
      "name": "Angola",
      "cca2": "AO",
      "calling-code": "244"
    }, {
      "name": "Anguilla",
      "cca2": "AI",
      "calling-code": "1264"
    }, {
      "name": "Antigua and Barbuda",
      "cca2": "AG",
      "calling-code": "1268"
    }
     ]

我想迭代这个列表并创建如下的选择列表

<select>
   <option value="AF">Afganisthan</option>
   ....
<select>

我做了这个

for (var i = 0; i < countries.length; i++) {
    out += "<option value='" + countries[i].cca2 + "'>" + countries[i].name + "</option>";
}

但没有出现......

5 个答案:

答案 0 :(得分:0)

试试这个:

for(var i=0;i<countries.length;i++){
    $('select').append('<option value="'+countries[i].cca2+'">'+countries[i].name+'</option>');
}

答案 1 :(得分:0)

<select id='mySelect'><select>

$.each(countries, function(i, e){
    $('#mySelect').append("<option value='" + e.cca2 +"'>" + e.name + "</option>");
})

Demo

答案 2 :(得分:0)

    var obj = eval('{' + str + '}'); //where str is "countries: ..."
    $('<select>').appendTo(document.body);    
    for(var i = 0; i < obj.countries.length; i++)
    {
       $('<option>').val(obj.countries[i].cca2).text(obj.countries[i].name).appendTo('select');
    }

答案 3 :(得分:0)

var out = '<select>';

countries.forEach(function(country) {
    out += '<option value=' + country.cca2 + '>' + country.name + '</option>';
});

out += '</select>';

答案 4 :(得分:0)

尝试下面的javascript代码段

var countryJSON= eval('{'+countryString+'}');
$('<select>').appendTo("#yourForm");    
for(i=0;i<countryJSON['countries'].length;i++){    
 $('<option>').val(countryJSON.countries[i].cca2).text(countryJSON.countries[i].name).appendTo('select');
}