首页 > 解决方案 > 使用 ES5 .map 和 jQuery 元素

问题描述

以下代码如何使用ES5 .map函数,而不是 jQuery .map?

        const newList = new Array();
        $(".something").each((_, opt2) => {
            const val2 = $(opt2).val();
            ddl2Vals.push(val2);
        })

我试过但失败了:

const newList = $(".something").map(x => $(x).val());

编辑包括类:这是错字。

标签: javascriptjqueryecmascript-5map-function

解决方案


我将假设您的真实代码使用返回多个元素的选择器(#somethingID 选择器;ID 在文档中应该是唯一的)。

正如prasanth 所说,您可以在最后使用从 jQuery 对象获取真正的数组,尽管您需要记住 jQuery和 Arrayget之间的区别(使用 jQuery,回调的第一个参数是索引,而不是元素)。mapmap

如果你真的想使用Array's map,你可以通过 using 来做到这一点Function.prototype.call,像这样:

const newList = Array.prototype.map.call($("some-selector"), opt2 => $(opt2).val());

但是ES2015增加了Array.from,可以做映射;有关详细信息,请参阅Bergi 的答案(最后一个代码片段)。


旁注:如果opt2input, select, 或option元素,则无需使用 jQuery 来获取其值:

const newList = Array.prototype.map.call($("some-selector"), opt2 => opt2.value);

或者,Array.from正如 Bergi 指出的那样:

const newList = Array.from($("some-selector"), opt2 => opt2.value);

推荐阅读