我有一个数组,我想对它进行排序。然而;我有一个空的下拉菜单,我想填充。我卡住了。如何使用已排序的数组填充我的下拉菜单。
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",
答案 0 :(得分:3)
您可以for loop
将其写入innerHTML
select
来执行此操作
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;