第一種--對(duì)象鍵值去重
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 }
第二種--splice刪除去重
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 }
第三種--利用數(shù)組indexOf方法
// 循環(huán)遍歷當(dāng)前數(shù)組,當(dāng)前不在臨時(shí)數(shù)組的,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 }
第四種--數(shù)組下標(biāo)
// 當(dāng)前數(shù)組的第i項(xiàng)在當(dāng)前數(shù)組第一次出現(xiàn)的位置不是i,當(dāng)前項(xiàng)即重復(fù),反之 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 }
第五種
// 先排序,找相鄰的項(xiàng) // 這個(gè)會(huì)改變?cè)瓉?lái)數(shù)組的順序 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 }
第六種
// 優(yōu)化遍歷數(shù)組 // 獲取沒(méi)重復(fù)的最右一值放入新數(shù)組 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 }
第七種--es6 set
Array.prototype.unique7 = function () { var temp = new Set(this) return [...temp] }
第八種--filter
Array.prototype.unique8 = function () { return this.filter(function (ele, index, self) { return self.indexOf(ele) === index; }) }
以上所述是小編給大家介紹的javascript數(shù)組去重方法詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com