[英]How do I delete one item from an array with chrome.storage.sync.remove?
[英]chrome.storage.sync.remove array doesn't work
我正在制作一个小型 Chrome 扩展程序。 我想使用chrome.storage
但我无法让它从存储中删除多个项目(数组)。 单项删除工作。
function clearNotes(symbol)
{
var toRemove = "{";
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
toRemove += "'" + index + "',";
});
if (toRemove.charAt(toRemove.length - 1) == ",") {
toRemove = toRemove.slice(0,- 1);
}
toRemove = "}";
alert(toRemove);
});
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value) {
alert(index);
});
});
});
};
似乎没有任何问题,但最后一个提醒存储中内容的循环仍然显示我要删除的所有值。
当您将字符串传递给sync.remove
,Chrome会尝试删除其键与输入字符串匹配的单个项目 。 如果需要删除多个项目,请使用一组键值。
此外,您应该将remove
调用移至get
回调内部。
function clearNotes(symbol)
{
// CHANGE: array, not a string
var toRemove = [];
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
// CHANGE: add key to array
toRemove.push(index);
});
alert(toRemove);
// CHANGE: now inside callback
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
alert(index);
});
});
});
});
};
稍微苗条和更新的解决方案
chrome.storage.sync.get(null, (data) => {
const keys = Object.keys(data).filter((x) => x.startsWith('<start-of-key>')); // Can replace `startsWith` with regex or any other string comparison
chrome.storage.sync.remove(keys);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.