如何使用JS使用嵌套数组填充HTML下拉列表?

时间:2018-09-27 20:02:57

标签: javascript

我想使用此数组填充下拉菜单。我只希望“行星”位于下拉列表中,而不是数字。我认为它可能大致如下:

for (var i = 0; i < arr.length; i++) {
  var option = document.createElement("OPTION"),
    txt = document.createTextNode(arr[i]);
  option.appendChild(txt);
  option.setAttribute("value", arr[i]);
  select.insertBefore(option, select.lastChild);
}

但是我不确定如何仅访问行星...

var planets = [
  ['Pluto', 0.06],
  ['Neptune', 1.148],
  ['Uranus', 0.917],
  ['Saturn', 1.139],
  ['Jupiter', 2.640],
  ['Mars', 0.3895],
  ['Moon', 0.1655],
  ['Earth', 1],
  ['Venus', 0.9032],
  ['Mercury', 0.377],
  ['Sun', 27.9]
];

谢谢。

4 个答案:

答案 0 :(得分:1)

您可以使用array destructuring立即将内部数组放入变量textContentvalue中,然后使用Object.assign

将它们应用于选项元素
planets.forEach( ( [ textContent, value ] ) => { 
  let option = Object.assign(document.createElement( "OPTION" ), {textContent, value});
  select.appendChild( option ) 
});

var select = document.querySelector("select"), planets = [['Pluto', 0.06],['Neptune', 1.148],['Uranus', 0.917],['Saturn', 1.139],['Jupiter', 2.640],['Mars', 0.3895], ['Moon', 0.1655],['Earth', 1], ['Venus', 0.9032], ['Mercury', 0.377],['Sun', 27.9]];



planets.forEach( ( [ textContent, value ] ) => { 
  let option = Object.assign( document.createElement( "OPTION" ), { textContent, value } );
  select.appendChild( option ) 
});
<select></select>

答案 1 :(得分:0)

我认为这就是您所需要的:

for(var i = 0; i < arr.length; i++) {
  var option = document.createElement("option"),
  // Note that I've added a [0]. That's because arr[i] is still an array that contains the "planet" name ([0]) and the value ([1]) (on first and second position respectively)
  // I've also added the "var" keyword to avoid generating a global variable with txt
  var txt = document.createTextNode(arr[i][0]);
  option.appendChild(txt);
  // Here too! The [1] was needed to get the value
  option.setAttribute("value", arr[i][1]);
  select.insertBefore(option, select.lastChild);
}

答案 2 :(得分:0)

如果要获取名称或值,则必须从内部数组访问值。

arr[i][0]是名称,arr[i][1]是值:

var arr = [
  ['Pluto', 0.06],
  ['Neptune', 1.148],
  ['Uranus', 0.917],
  ['Saturn', 1.139],
  ['Jupiter', 2.640],
  ['Mars', 0.3895],
  ['Moon', 0.1655],
  ['Earth', 1],
  ['Venus', 0.9032],
  ['Mercury', 0.377],
  ['Sun', 27.9]
];

let select = document.querySelector("select")

for (var i = 0; i < arr.length; i++) {
  var option = document.createElement("OPTION"),
    txt = document.createTextNode(arr[i][0]);
  option.appendChild(txt);
  option.setAttribute("value", arr[i][1]);
  select.insertBefore(option, select.lastChild);
}
<select></select>

答案 3 :(得分:-1)

因为您在Array内部有Array。因此,您必须迭代两次以获取所有值,或者如果要对其进行硬编码,则必须迭代一次。

 for(i = 0; i < arr.length; i++){
     var value = arr[i][0]
 }