Javascript 如何仅映射选定元素的选中选项

Javascript 如何仅映射选定元素的选中选项,javascript,Javascript,我需要将select element multiple selection中的所选选项映射到一个数组 以下是html: <select id="listado" size="5" multiple> <option value="Leer" id="aficion-leer">Leer</option> <option value="Programa

我需要将select element multiple selection中的所选选项映射到一个数组

以下是html:

<select id="listado" size="5" multiple>
    <option value="Leer" id="aficion-leer">Leer</option>
    <option value="Programar" id="aficion-programar">Programar</option>
    <option value="Cine" id="aficion-cine">Cine</option>
    <option value="Deporte" id="aficion-deporte">Deporte</option>
</select>
我试过这个: Array.fromdocument.querySelectorlistado.mapelemento=>elemento.value;它返回所有选项。根据,将option:checked添加到查询参数应该可以做到这一点,但我得到一个空列表

知道原因是什么吗?

您可以使用document.querySelectorAll,只选择选中的选项,然后映射它们

let options=[…document.querySelectorAlllistado选项:选中].maplemento=>elemento.value 控制台。登录选项 色咪咪地看 程序 电影 驱逐出境 您可以使用document.queryselectoral,只选择选中的选项,然后映射它们

let options=[…document.querySelectorAlllistado选项:选中].maplemento=>elemento.value 控制台。登录选项 色咪咪地看 程序 电影 驱逐出境 你试过这个吗

console.log Array.fromdocument.querySelectorlistado.childNodes.filterelemento=>elemento.selected.mapelemento=>elemento.value//此行 ; 色咪咪地看 程序 电影 驱逐出境 你试过这个吗

console.log Array.fromdocument.querySelectorlistado.childNodes.filterelemento=>elemento.selected.mapelemento=>elemento.value//此行 ; 色咪咪地看 程序 电影 驱逐出境
三个圆点在这里做什么?我原以为它们是用来复制对象的,但我不知道这在这种情况下会有什么用处,但是没有它们它就不行了。@LuisFernandez,它的扩展运算符在这里读到了:这是因为QuerySelector会返回一个列表,而不是数组,所以你必须将这些列表项放入数组中才能映射它。没错,但是使用Array.from更安全。您可以在不使用扩展运算符的情况下对每个对象使用,然后从列表中推送值:let options=[]document.querySelectorAlllistado option:checked.forEachelemento=>options.pushelemento.value@LuisFernandez@blaumeise20怎么样?这三个点是干什么的?我原以为它们是用来复制对象的,但我不知道这在这种情况下会有什么用处,但是没有它们它就不行了。@LuisFernandez,它的扩展运算符在这里读到了:这是因为QuerySelector会返回一个列表,而不是数组,所以你必须将这些列表项放入数组中才能映射它。没错,但是使用Array.from更安全。您可以在不使用扩展运算符的情况下对每个对象使用,然后从列表中推送值:let options=[]document.querySelectorAlllistado option:checked.forEachelemento=>options.pushelemento.value@LuisFernandez@blaumeise20怎么样?