我正在尝试构建注册表并使用本地存储来保存详细信息。在向 locastorage 添加另一个表单详细信息时,我想知道最后插入的键的值是多少,以便我可以递增它并可以插入具有递增键值的新记录。
如何实现。如果我删除任何记录,我当前的代码将覆盖这些值,因为我正在计算存储中可用的键数。
function setlocal(){
var o = {};
var ff = $('#myform').serializeArray();
$.each(ff, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
var tt = JSON.stringify(o);
localStorage.setItem(localStorage.length+1, tt);
$('#afterInsert').text('data added sucessfully');
return true;
}
有什么建议吗?
最佳答案
为什么不能将最后插入的键存储在单独的属性中
var lastKey = parseInt(localStorage.getItem('lastKey'));
var newKey = lastKey + 1 || 1;
localStorage.setItem(newKey , tt);
localStorage.setItem('lastKey', newKey);
关于javascript - 如果我只使用整数作为键,如何在本地存储中获取最后插入的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524049/