我正在尝试将过去的搜索添加到本地存储并使用数组来执行此操作。问题是它会将值添加两次,即使只有一次调用该函数。对于每个新的、不同的搜索,我希望将其添加到我的数组和存储中,如果超过五个,则弹出最后一项。
处理搜索时调用:
SetLocalStorageItem(searchString[1]);
应该这样做的功能:
function SetLocalStorageItem(search) {
if(search === '') {
return;
}
console.log(localStorage);
// Check if the browser support Local Storage
if(localStorage) {
if(localStorage["pastSearches"]) {
pastSearches.push(JSON.parse(localStorage["pastSearches"]));
}
// Check if the value exists in the array,
// returns -1 if the array does not contain the value
if($.inArray(search, pastSearches) == -1) {
// If not, put it first and...
pastSearches.unshift(search);
// ...pop one at the end if array is too big
if(pastSearches.length > 5) {
pastSearches.pop();
}
pastSearches.push(search);
// Adding the search to the storage
localStorage["pastSearches"] = JSON.stringify(pastSearches);
DisplayPastSearches();
}
}
}
清除和显示功能:
function ClearSearches() {
// If there is any past searches
localStorage.clear();
pastSearches = [];
}
function DisplayPastSearches() {
if(pastSearches.length) {
$("<div>" + pastSearches + "</div>").appendTo(".container");
}
}
现在,如果我清除搜索数组并且存储为空,然后运行代码并搜索“billy”,上面的console.log提示:
Storage
length: 1
pastSearches: "["billy","billy"]"
__proto__: Storage