【发布时间】:2010-07-06 17:06:29
【问题描述】:
我有两个数组,想从一个数组中删除另一个数组中存在的所有元素。
- 这可以用原生 JS 完成吗?
- 有 jQuery 函数来做吗?
- 这样做的最佳做法是什么( 越快越好)
p.s.:也可以用其他语言发布代码,也许我可以将其移植到 Javascript
更新,在接受回答后帮助 JS 帅哥 ;-)
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
// Array Contains - By Helmuth Lammer (TU Vienna)
Array.prototype.contains = function(key){
for(var i = 0; i<this.length; i++){
if(this[i] == key) return i;
}
return false;
}
(还有一个名为 contains 的原生 JS 方法,但应该可以)
【问题讨论】:
-
替换成什么?你想合并它们吗?
-
@galam 他想让 A 和 B 不相交,让 A 保持不变。
-
对不起我的错*displace
-
现在我真的不明白你的意思。您的意思是“删除”以便 A 中的项目不会像 @glowcoder 建议的那样出现在 B 中吗?
-
我的英语太糟糕了。删除是正确的。对此感到抱歉。在几分钟内试用@glowcoders 解决方案...
标签: javascript jquery arrays