Javascript 如何从字符串创建关联数组?
这就是我所拥有的:Javascript 如何从字符串创建关联数组?,javascript,jquery,arrays,Javascript,Jquery,Arrays,这就是我所拥有的: <input type="checkbox" name="selectedId[{{ order.id }}]"> const orders = []; $("input[type=checkbox][name*='selectedId']:checked").each(function (index) { let id = $(this).attr('name').match
<input type="checkbox" name="selectedId[{{ order.id }}]">
const orders = [];
$("input[type=checkbox][name*='selectedId']:checked").each(function (index) {
let id = $(this).attr('name').match(/[-0-9]+/);
orders[index] = id[0];
});
我想得到的是:
orders = [
0 => ["id" => 1],
1 => ["id" => 2]
];
订单[索引][“id”]=id[0]不起作用
Javascript有对象,而不是关联数组。为了达到您想要的效果,您需要以下内容:
let orders = [];
$("input[type=checkbox][name*='selectedId']:checked").each(function (index) {
orders[index] = { id: $(this).attr('name').match(/[-0-9]+/)[0] };
});
或者你也可以使用
此外,它用于不可变常量,因此您可能希望使用它来代替。
orders[index]={id:id[0]}代码>
let orders = [];
$("input[type=checkbox][name*='selectedId']:checked").each(function (index) {
orders[index] = { id: $(this).attr('name').match(/[-0-9]+/)[0] };
});
orders.push({ id: $(this).attr('name').match(/[-0-9]+/)[0] });