小程序封装本地历史搜索类

话不多说上代码,相当于实现一个数据结构中的队列 / 栈:

class KeywordsModel {

  // 存储key
  key = 'q'
  // 历史条目最大长度
  maxLength = 10

  // 获取历史纪录的一个数组
  getHistory(keyword){
    const words = wx.getStorageSync(this.key)
    if (!words){
      return []
    }
    return words
  }

  // 添加到历史纪录
  addToHistory(keyword){
    // 类似长度为10的栈 队列
    let words = this.getHistory()
    // 判断历史数据是否已经存在
    const has = words.includes(keyword)
    if(!has){
      if (words.length >= this.maxLength){
        // 如果大于最大长度 则删除最后一项
        words.pop()
      }
      // 添加至数组的首项
       words.unshift(keyword)
    }
    // 存入小程序缓存中
    wx.setStorageSync(this.key, words)
  }

}

 

posted @ 2019-06-17 21:09  博客小鹏鹏  阅读(240)  评论(0编辑  收藏  举报