更新时间:2022-02-05 22:15:49
因为我在@Rocket答案的评论中继续讨论它,我也可以提供一个不使用库的示例。这需要两个新的原型函数,包含
和唯一
Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains
and unique
Array.prototype.contains = function(v) {
for(var i = 0; i < this.length; i++) {
if(this[i] === v) return true;
}
return false;
};
Array.prototype.unique = function() {
var arr = [];
for(var i = 0; i < this.length; i++) {
if(!arr.includes(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
然后你可以这样做:
var duplicates = [1,3,4,2,1,2,3,8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]
为了获得更高的可靠性,你可以用MDN的 indexOf
shim替换包含
并检查每个元素的 indexOf
等于-1: https://developer.mozilla.org/ en / JavaScript / Reference / Global_Objects / Array / indexOf
For more reliability, you can replace contains
with MDN's indexOf
shim and check if each element's indexOf
is equal to -1: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf