javascript - 使用 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());
编辑包括类:这是错字。
解决方案
我将假设您的真实代码使用返回多个元素的选择器(#something
是ID 选择器;ID 在文档中应该是唯一的)。
正如prasanth 所说,您可以在最后使用从 jQuery 对象获取真正的数组,尽管您需要记住 jQuery和 Arrayget
之间的区别(使用 jQuery,回调的第一个参数是索引,而不是元素)。map
map
如果你真的想使用Array
's map
,你可以通过 using 来做到这一点Function.prototype.call
,像这样:
const newList = Array.prototype.map.call($("some-selector"), opt2 => $(opt2).val());
但是ES2015增加了Array.from
,可以做映射;有关详细信息,请参阅Bergi 的答案(最后一个代码片段)。
旁注:如果opt2
是input
, 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);
推荐阅读
- javascript - 在提交之前使用 JavaScript 更改 HTML 表单值
- javascript - 如何在 Vanilla Js 中通过 replace() 使用动态数据更改重复项
- java - 为什么Java中的replaceAll()方法认为字符串“:n”与“.n”相同?
- mysql - Excel公式无需编码即可将范围内的多个元素插入到sql列中?
- c# - .net WebSocketClient 的 ConnectAsync 类抛出错误“无法访问已处置的对象 ClientWebSocket”。
- excel - 查找两个 Excel 工作表之间的共享数据
- android - 如何给android mapbox充气?
- sql-server - Maven liquibase 没有替换所有属性
- python - TypeError: len 对于符号张量没有很好的定义。(activation_3/Identity:0) 请调用 `x.shape` 而不是 `len(x)` 获取形状信息
- php - 如何从 Laravel 的另一个数据库表中获取一个表的值