searchHistory

247 阅读1分钟

function setHistory (keyword) {    
    let list = localStorage.getItem('historySearch')
    if(list){
      list = JSON.parse(list)
      let index = list.indexOf(keyword)
      if(index!=-1){ // 去重
        list.splice(index, 1)
      }
      list.unshift(keyword)
      if(list.length > 8){ // 最多8条历史记录
        list.splice(list.length-1)
      }
      localStorage.setItem('historySearch',JSON.stringify(list))
    }else{
      localStorage.setItem('historySearch',JSON.stringify([keyword]))
    }
}