我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在Stack Overflow上找到了另一个脚本,看起来几乎与它完全一样,但它不会失败。
所以为了帮助我学习,有人能帮我确定原型脚本哪里出错吗?
Array.prototype.getUnique = function() {
var o = {}, a = [], i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
for (e in o) {a.push (e)};
return a;
}
重复问题的更多答案:
从JS数组中删除重复值
类似的问题:
获取数组中的所有非唯一值(即:重复/多次出现)
一个简单的代码如下:
let arr = [1,'k',12,1,1,'k','12'];
let distictArr=arr.filter((item, index, arr) => arr.indexOf(item) === index);
console.log(distictArr); // [1, 'k', 12, '12']
使用Set删除重复项。
具有重复项的阵列
const withDuplicates = [2, 2, 5, 5, 1, 1, 2, 2, 3, 3];
使用Set获取不重复的新数组
const withoutDuplicates = Array.from(new Set(withDuplicates));
较短版本
const withoutDuplicates = [...new Set(withDuplicates)];
结果:[2,5,1,3]