【发布时间】:2010-07-04 05:07:53
【问题描述】:
我有一个项目数组(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,如果它有所作为的话。
更新基于@Matthew Flaschen 的回答:
// 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() 返回 false,因为我正在寻找的重复项在 == 意义上并不严格相等。但是,它们的所有值都是相同的。我可以让这个更简洁吗?
【问题讨论】:
-
splice并不是很快。最好将所选项目添加到新数组中,而不是从原始数组中删除其余部分。
标签: javascript arrays object