如何使用排序数组填充下拉菜单

时间:2016-03-18 00:34:09

标签: javascript html arrays

我有一个数组,我想对它进行排序。然而;我有一个空的下拉菜单,我想填充。我卡住了。如何使用已排序的数组填充我的下拉菜单。

enter code here
<select id="dropdownList">
<option></option>
</select>

enter code here

var array = ["vintage","frames","treats","engraved", "stickers", "jewelerybox", "flask"];

array.sort(function(val1 , val2){
  return val1.localeCompare(val2);
});

console.log(array); // ["engraved", "flask", "frames", "jewelerybox", "stickers", "treats",

1 个答案:

答案 0 :(得分:3)

您可以for loop将其写入innerHTML

select来执行此操作

&#13;
&#13;
var array = ["vintage", "frames", "treats", "engraved", "stickers", "jewelerybox", "flask"];

array.sort(function(val1, val2) {
  return val1.localeCompare(val2);
});

var select = document.getElementById("dropdownList");

for (var i = 0; i < array.length; i++) {

  select.innerHTML += '<option>' + array[i] + '</option>';

}
&#13;
<select id="dropdownList">

</select>
&#13;
&#13;
&#13;