unique:數組去重,返回一個新數組


function unique(arr){ 
  if(!isArrayLink(arr)){ //不是類數組對象

    return arr

  }

  let result = []

  let objarr = []

  let obj = Object.create(null)

  arr.forEach(item => {

    if(isStatic(item)){//是除了symbol外的原始數據

      let key = item + '_' + getRawType(item);

      if(!obj[key]){

        obj[key] = true

        result.push(item)

      }

    }else{//引用類型及symbol

      if(!objarr.includes(item)){

        objarr.push(item)

          result.push(item)

      }

    }

  })

  return resulte
}


Set簡單實現

 

window.Set = window.Set || (function () { 
  function Set(arr) {

    this.items = arr ? unique(arr) : [];

    this.size = this.items.length; // Array的大小

  }

  Set.prototype = {

    add: function (value) {

      // 添加元素,若元素已存在,則跳過,返回 Set 結構本身。

      if (!this.has(value)) {

        this.items.push(value);

        this.size++;

      }

      return this;

    },

    clear: function () {

      //清除所有成員,沒有返回值。

      this.items = []

      this.size = 0

    },

    delete: function (value) {

      //刪除某個值,返回一個布爾值,表示刪除是否成功。

      return this.items.some((v, i) => {

        if(v === value){

          this.items.splice(i,1)

          return true

        }

        return false

      })

    },

    has: function (value) {

      //返回一個布爾值,表示該值是否為Set的成員。

      return this.items.some(v => v === value)

    },

    values: function () {

      return this.items

    },

  }

  return Set;
}());



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM