同一循环中的多个 appendChild 调用

Multiple appendChild calls in the same loop

listCities.forEach(function(city){
   let option = document.createElement('option');
   option.value = city;
   listFrom.appendChild(option);
   listTo.appendChild(option);

});

我有一个数组,我想将其中的每个字符串作为选项添加到两个数据列表(listFrom 和 listTo)。问题是无论我把它们放在哪个顺序,只有列表的最后一个得到添加到它们的选项。

有没有办法在同一个 forEach 循环中执行此操作,还是我必须创建两个不同的循环来执行完全相同的操作。

我只是无法理解其背后的逻辑。

一个元素只能存在于一处。你需要制作一个clone

const listFrom = document.querySelector('#from');
const listTo = document.querySelector('#to');

listCities = ["a","b","c","d"];

listCities.forEach(function(city){
   let option = document.createElement('option');
   option.textContent = city;
   option.value = city;
   listFrom.appendChild(option);
   listTo.appendChild(option.cloneNode(true));
});
<label for="from">From:</label><select id="from"></select>
<label for="to">To:</label><select id="to"></select>

当您追加子项时,您将元素移动到最后提到的容器中,因为该元素在 DOM 中仅存在一次。

这比创建一个选项、克隆它并附加它两次要快得多:

const listCities = ["Buenos Aires","Cordoba","Rosario","Mendoza","La Plata","Tucumán","Mar del Plata","Salta","Santa Fe","San Juan","Resistencia","Santiago del Estero","Corrientes","Neuquén","Posadas","San Salvador de Jujuy","Bahía Blanca","Paraná","Formosa","San Fernando del Valle de Catamarca","San Luis","La Rioja","Comodoro Rivadavia","Río Cuarto"], 
  listFrom = document.getElementById("from"), 
  listTo   = document.getElementById("to");

const options = listCities
  .map(city => `<option value="${city}">${city}</option>`)
  .join("");
listFrom.innerHTML += options;
listTo.innerHTML   += options;
<select id="from"><option value="">From city</option></select> <select id="to"><option value="">To city</option></select>