我有一系列物品(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