如何比较数组中的项目并替换,并在特定索引处设置索引?

下面是在 html 和简单的 JavaScript 中运行代码以在 select 元素中显示项目。目前选择的项目来自options数组,还有一个名为days的数组


在这里,我想将数组选项与天数以及任何项目索引到天数相似的天数进行比较,我想将它们放入选项数组中。因此,在比较数组之后,我的选项数组将类似于天数组。因此下拉菜单应按顺序显示项目,例如“日”、“周”、“月”、“年”、“六个月”,这应该来自选项数组


var options = ["day", "yearly","week", "sixmonth",'month'];


var days = ['day','week','month','yearly','sixmonth']

var s = document.getElementById("selectCity");

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

  s.innerHTML += `<option value=${i}> ${options[i]}</option>`;

}

 <select id="selectCity">

        <option>Choose a City</option>

      </select>


一只甜甜圈
浏览 134回答 2
2回答

墨色风雨

假设 days 是选项的子集,并且您希望所有选项数组值都按照天数的项目索引进行排序。并且选项数组中的任何额外项目最终都会按照它们的出现顺序出现。这是代码&nbsp; &nbsp; &nbsp; var options = ["day", "yearly","week", "sixmonth",'month',"newMonth"];&nbsp; &nbsp; &nbsp; var days = ['day','week','month','yearly','sixmonth']&nbsp; &nbsp; &nbsp; var sorted=days.filter(val=>options.includes(val))&nbsp; &nbsp; &nbsp; options = options.filter(val => !days.includes(val))&nbsp; &nbsp; &nbsp; sorted.push(...options)&nbsp; &nbsp; &nbsp; console.log(sorted)&nbsp; &nbsp; &nbsp; var s = document.getElementById("selectCity");&nbsp; &nbsp; &nbsp; for (var i = 0; i < sorted.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.innerHTML += `<option value=${i}> ${sorted[i]}</option>`;&nbsp; &nbsp; &nbsp; }

慕雪6442864

我认为选项是天的子集,并且您希望对选项进行排序,使其与天具有相同的顺序。这是一个例子:var options = ["day", "yearly","week", "sixmonth",'month'];var days = ['day','week','month','yearly','sixmonth'];var sortedOptions = options.sort((a, b) => days.indexOf(a) - days.indexOf(b))var s = document.getElementById("selectCity");for (var i = 0; i < sortedOptions.length; i++) {&nbsp; &nbsp; s.innerHTML += `<option value=${i}> ${sortedOptions[i]}</option>`;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript