国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

javascript數組去重方法總結(推薦)

2024-05-06 16:49:16
字體:
來源:轉載
供稿:網友

 第一種--對象鍵值去重

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  }

第三種--利用數組indexOf方法

// 循環遍歷當前數組,當前不在臨時數組的,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  }

第七種--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數組去重方法詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 博乐市| 淮北市| 湛江市| 驻马店市| 三明市| 灵丘县| 营口市| 安丘市| 伊宁市| 牙克石市| 天台县| 北流市| 六盘水市| 独山县| 清水县| 雅安市| 卢龙县| 南宁市| 南汇区| 钦州市| 舒兰市| 绍兴县| 武威市| 崇仁县| 赤峰市| 三都| 陕西省| 二手房| 临高县| 临沧市| 太白县| 玛纳斯县| 定西市| 汾西县| 怀宁县| 清苑县| 徐闻县| 谢通门县| 霍城县| 河源市| 乐昌市|