gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:03:12 25 4
gpt4 key购买 nike

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

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",

最佳答案

你可以使用for循环,将它写入selectinnerHTML

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>';

}
<select id="dropdownList">

</select>

关于javascript - 如何使用排序数组填充下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com