代码之家  ›  专栏  ›  技术社区  ›  Abhijeet

将ES6.map与jQuery元素一起使用

  •  -1
  • Abhijeet  · 技术社区  · 4 年前

    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());
    

    编辑以包含类:这是打字错误。

    2 回复  |  直到 4 年前
        1
  •  2
  •   T.J. Crowder    4 年前

    你可以用 .get() 最后

    $("#something").map((_, x) => $(x).val()).get()
    
        2
  •  2
  •   T.J. Crowder    4 年前

    #something 是一个 ID选择器

    作为 prasanth said ,你可以使用 get 最后,从jQuery对象获得一个真正的数组,尽管您需要记住jQuery map 和数组的 map (对于jQuery,回调的第一个参数是索引,而不是元素)。

    Array 地图 Function.prototype.call ,例如:

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

    但是 ES2015新增 Array.from ,可以进行映射;看见 Bergi's answer for details


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

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

    或者,再一次,用 Array.from

    const newList = Array.from($("some-selector"), opt2 => opt2.value);
    
        3
  •  1
  •   Bergi    4 年前

    使用 map 方法 Array ,首先使用将jQuery集合转换为数组 .toArray

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

    Array.from :

    const newList = Array.from($(".something")).map(x => x.value);
    

    在那里你甚至不需要使用 .map()

    const newList = Array.from($(".something"), x => x.value);