Javascript 如何删除存储在localStorage中的对象的属性?
在localStorage中,我有一个对象记录。它有很多领域 记录[recordId],我希望能够删除这些条目。下面是我的删除功能,但它不工作。所有记录都会附加到本地存储中的records对象。不确定是什么错,因为我正在以正确的方式删除。当我打印记录对象时,所有记录及其密钥仍在那里Javascript 如何删除存储在localStorage中的对象的属性?,javascript,Javascript,在localStorage中,我有一个对象记录。它有很多领域 记录[recordId],我希望能够删除这些条目。下面是我的删除功能,但它不工作。所有记录都会附加到本地存储中的records对象。不确定是什么错,因为我正在以正确的方式删除。当我打印记录对象时,所有记录及其密钥仍在那里 function deleteLocalRecord(recordId) { var records = localStorage.getItem('records'); var theRecor
function deleteLocalRecord(recordId) {
var records = localStorage.getItem('records');
var theRecords;
if (supports_html5_storage()) {
if (records == null) {
theRecords = {};
} else {
// parse the records
theRecords = JSON.parse(records);
}
theRecords[recordId] = ''; // set the record to empty string.
delete theRecords[recordId]; // delete the record
// reset the records object in local storage after change
localStorage.setItem('records', JSON.stringify(theRecords));
}
}
function supports_html5_storage()
{
try
{
return 'localStorage' in window && window['localStorage'] !== null;
}
catch (e)
{
return false;
}
}
这里有一个全局变量,一个函数也支持html5存储。。。我怀疑没有人能在不知道它们是什么的情况下提供帮助?如果它返回false,那么这个函数将什么也不做。对不起,我更新了上面的内容。支持本地存储只是检查是否支持本地存储。代码肯定会运行。但是我注意到我不能在delete命令行上设置断点。@Javascripter mmhmm。它工作正常吗?你确定内部代码被命中了吗?我通过chrome调试器运行了它,它执行了,但似乎可能跳过了删除。它似乎跳转到下面的行。是的,这确实正确运行,在我的例子中,记录看起来更像:testt:{t1:t1val,t2:t2Val}不确定这是否是差异。好的。它确实有效。问题是我在循环通过并调用deleteLocalRecord后重置了记录。
function deleteLocalRecord(recordId) {
if (localStorageEnabled()) {
var records = localStorage.getItem('records'),
theRecords = JSON.parse(records) || {};
print(JSON.stringify(theRecords)); // before
delete theRecords[recordId]; // delete
print(JSON.stringify(theRecords)); // after
localStorage.setItem('records', JSON.stringify(theRecords));
print(localStorage.getItem("records"));
}
}
var records = {
"test": "test",
"stuff": "stuff"
};
localStorage.setItem("records", JSON.stringify(records));
deleteLocalRecord("test");
function print(x) {
document.body.innerHTML += "<p>" + x + "</p>";
};
function localStorageEnabled() {
return typeof window["localStorage"] !== "undefined";
};