var arr = [1, 1, '1', '1', null, null, undefined, undefined, new String('1'), new String('1'), /a/, /a/, NaN, NaN];复制代码
兼容性好 数组
'1'和1能够区分bash
对象不能够去重 由于对象不能够用来比较 学习
NaN不能够去重ui
Array.prototype.unique = function () {
var newArr = [],
isRepeat,
len = this.length;
for (var i = 0; i < len; i++) {
isRepeat = false;
for (var j = 0; j < newArr.length; j++) {
if (this[i] === newArr[j]) {
isRepeat = true;
break;
}
}
if (!isRepeat) {
newArr.push(this[i]);
}
}
return newArr;
}复制代码
'1'和1能够区分this
对象不能够去重 由于对象不能够用来比较spa
NaN不能够去重prototype
Array.prototype.unique = function() {
var res = [],
len = this.length;
for (var i = 0; i < len; i++) {
var current = this[i];
if (res.indexOf(current) === -1) {
res.push(current);
}
}
return res;
}复制代码
'1'和1能够区分code
对象不能够去重 由于对象不能够用来比较对象
NaN不能够去重get
不能识别undefined
Array.prototype.unique = function () {
var newArr = [],
len = this.length;
this.sort(function(a, b) { // 改变原数组
return a-b;
});
for (var i = 0; i < len; i++) {
if (this[i] !== this[i + 1]) {
newArr.push(this[i]);
}
}
return newArr;
}复制代码
'1'和1能够区分
对象不能够去重 由于对象不能够用来比较
NaN识别不了
Array.prototype.unique = function() {
var res = this.filter(function(item, index, array){
return array.indexOf(item) === index;
})
return res;
}复制代码
NaN能够去重
对象不能够去重 由于对象不能够用来比较
Array.prototype.unique = function () {
var newArr = [];
this.forEach(item => {
if (!newArr.includes(item)) {
newArr.push(item);
}
});
return newArr;
}复制代码
能够区分'1'和1
对象不能够区分
NaN不能够区分
Array.prototype.unique = function () {
return this.sort().reduce((init, current) => {
if (init.length === 0 || init[init.length - 1] !== current) {
init.push(current);
}
return init;
}, []);
}复制代码
NaN能够去重
正则能够去重
'1'和1不能区分
对象不能够去重 由于对象做为 key 会变成 [object Object]
Array.prototype.unique = function () {
var obj = {},
arr = [],
len = this.length;
for (var i = 0; i < len; i++) {
if (!obj[this[i]]) {
obj[this[i]] = 'abc'; // 不能是 = this[i] 万一数组去重0
arr.push(this[i]);
}
}
return arr;
}
// 改变版本1
Array.prototype.unique = function () {
const newArray = [];
const tmp = {};
for (let i = 0; i < this.length; i++) {
if (!tmp[typeof this[i] + this[i]]) {
tmp[typeof this[i] + this[i]] = 1;
newArray.push(this[i]);
}
}
return newArray;
}
// 改进版本2
Array.prototype.unique = function () {
const newArray = [];
const tmp = {};
for (let i = 0; i < this.length; i++) {
// 使用JSON.stringify()进行序列化
if (!tmp[typeof this[i] + JSON.stringify(this[i])]) {
// 将对象序列化以后做为key来使用
tmp[typeof this[i] + JSON.stringify(this[i])] = 1;
newArray.push(this[i]);
}
}
return newArray;
}
复制代码
NaN能够去重
对象不能够去重
Array.prototype.unique = function () {
var newArr = [],
tmp = new Map(),
len = this.length;
for (var i = 0; i < len; i++) {
if (!tmp.get(this[i])) {
tmp.set(this[i], 1);
newArr.push(this[i]);
}
}
return newArr;
}
//简化版
Array.prototype.unique = function() {
var map = new Map()
return arr.filter((a) => !map.has(a) && map.set(a, 1))
}复制代码
NaN去重
对象不能够去重
Array.prototype.unique = function () {
return [...new Set(this)];
}复制代码
你的点赞是我持续输出的动力 但愿能帮助到你们 互相学习 有任何问题下面留言 必定回复