array.prototype.unique1 = function () { var r = {}, temp = [] for (var i = 0; i < this.length; i++) { if (!r[this[i]]) { r[this[i]] = 1 temp.push(this[i]) } } return temp }
array.prototype.unique2 = function () { for (var i = 0; i < this.length; i++) { for (var j = i + 1; j < this.length; j++) { if (this[i] === this[j]) { this.splice(j, 1) j-- } } } return this }
// 循环遍历当前数组,当前不在临时数组的,push array.prototype.unique3 = function () { var temp = [] for (var i = 0; i < this.length; i++) { if (temp.indexof(this[i]) === -1) temp.push(this[i]) } return temp }
// 当前数组的第i项在当前数组第一次出现的位置不是i,当前项即重复,反之 array.prototype.unique4 = function () { var temp = [this[0]] for (var i = 1; i < this.length; i++) { if (this.indexof(this[i]) === i) temp.push(this[i]) } return temp }
// 先排序,找相邻的项 // 这个会改变原来数组的顺序 array.prototype.unique5 = function () { var temparr = this.sort(), temp = [temparr[0]] for (var i = 1; i < temparr.length; i++) { if (temparr[i] !== temp[temp.length - 1]) temp.push(temparr[i]) } return temp }
// 优化遍历数组 // 获取没重复的最右一值放入新数组 array.prototype.unique6 = function () { var temp = [] for (var i = 0; i < this.length; i++) { for (j = i + 1; j < this.length; j++) { if (this[i] === this[j]) { i++; j = i; } } temp.push(this[i]) } return temp }
array.prototype.unique7 = function () { var temp = new set(this) return [...temp] }
array.prototype.unique8 = function () { return this.filter(function (ele, index, self) { return self.indexof(ele) === index; }) }
如对本文有疑问, 点击进行留言回复!!
vue源码实战render.js与$nextTick的异步调用
同事牛逼啊,写了个隐藏 bug,我排查了 3 天才解决问题!
【JavaScript笔记(一)】万丈高楼平地起 - 基本概念篇
网友评论