我有一系列物品(terms)
,這些物品將作爲<option>
標籤放在<select>
中。如果這些物品中有任何物品在另一個陣列中(termsAlreadyTaking
),應先將其移除。以下是我如何完成此操作:查看數組是否包含對象的更好方法?
// If the user has a term like "Fall 2010" already selected, we don't need that in the list of terms to add.
for (var i = 0; i < terms.length; i++)
{
for (var iAlreadyTaking = 0; iAlreadyTaking < termsAlreadyTaking.length; iAlreadyTaking++)
{
if (terms[i]['pk'] == termsAlreadyTaking[iAlreadyTaking]['pk'])
{
terms.splice(i, 1); // remove terms[i] without leaving a hole in the array
continue;
}
}
}
有沒有更好的方式來做到這一點?這感覺有點笨拙。
我使用jQuery,如果它的確與衆不同。
UPDATE基於@Matthew富蘭琛的回答:
// If the user has a term like "Fall 2010" already selected, we don't need that in the list of terms to add.
var options_for_selector = $.grep(all_possible_choices, function(elem)
{
var already_chosen = false;
$.each(response_chosen_items, function(index, chosen_elem)
{
if (chosen_elem['pk'] == elem['pk'])
{
already_chosen = true;
return;
}
});
return ! already_chosen;
});
它會在中間更詳細一點的原因是$.inArray()
正在恢復假的,因爲我在尋找重複的不嚴格相等彼此在==
感。但是,他們的所有價值都是一樣的。我可以使這更簡潔嗎?
'splice'是不完全的快。將所選項目添加到新數組可能會更好,而不是從原始數據中刪除其餘項目。 – casablanca 2010-07-04 05:23:43