簡體   English   中英

如何從字符串創建關聯數組?

[英]How can I create an associative array from a string?

這就是我所擁有的:

<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 => 1, 1 => 2]

我想得到的是:

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] };
});

或者你也可以使用Array.push()

orders.push({ id: $(this).attr('name').match(/[-0-9]+/)[0] });

此外, const用於非可變常量,因此您可能想改用let

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM