Javascript 如何使用chrome.storage.sync.remove从阵列中删除一项?
我正在构建一个Chrome浏览器扩展,其中包括一个允许用户保存URL的功能。我使用Javascript 如何使用chrome.storage.sync.remove从阵列中删除一项?,javascript,arrays,google-chrome-extension,google-chrome-storage,Javascript,Arrays,Google Chrome Extension,Google Chrome Storage,我正在构建一个Chrome浏览器扩展,其中包括一个允许用户保存URL的功能。我使用chrome.storage.sync创建了这个功能,没有遇到任何问题 但是,我还需要让用户删除他们已经保存的URL。我创建了一个文本输入框,他们可以在其中输入想要删除的单个url(即“www.url.com”)。我想把这个输入转换成一个字符串,当用户按下按钮时,用它从Chrome存储器中删除一个匹配的字符串 我认为指定可以使用chrome.storage.sync.remove从存储的数组中删除字符串,但我无法让
chrome.storage.sync
创建了这个功能,没有遇到任何问题
但是,我还需要让用户删除他们已经保存的URL。我创建了一个文本输入框,他们可以在其中输入想要删除的单个url(即“www.url.com”)。我想把这个输入转换成一个字符串,当用户按下按钮时,用它从Chrome存储器中删除一个匹配的字符串
我认为指定可以使用chrome.storage.sync.remove
从存储的数组中删除字符串,但我无法让它工作。这是我的密码:
function removeUrl() {
var theUrl = document.getElementById('url-input').value;
chrome.storage.sync.get(null, function(result, error) {
// Checks if the array (urlList) exists:
if ('urlList' in result) {
var theList = result['urlList'];
// Checks if the url that will be deleted is in the array:
if (theList.includes(theUrl)) {
chrome.storage.sync.remove(theUrl);
chrome.runtime.reload();
}
}
// Error handling goes here
});
}
这段代码不会抛出任何错误,但也不会从数组中删除url
请注意,我一次只想删除一个url,数组中没有重复的url,并且我没有使用任何像jQuery这样的库。我做错了什么 您不能这样做,因为
chrome.storage
是键值存储
在您的特定示例中,您试图从存储器中删除阵列的一个元素,但存储器仅包含带有阵列的密钥
这里最好的解决方案就是从数组中删除该值,然后再次将数组设置为chrome.storage
var theList = result['urlList'];
// Checks if the url that will be deleted is in the array:
if (theList.includes(theUrl)) {
// create a new array without url
var newUrlList = arr.filter(function(item) {
return item !== theUrl;
});
// set new url list to the storage
chrome.storage.sync.set({ 'urlList': newUrlList });
chrome.runtime.reload();
}
您不能这样做,因为
chrome.storage
是键值存储
在您的特定示例中,您试图从存储器中删除阵列的一个元素,但存储器仅包含带有阵列的密钥
这里最好的解决方案就是从数组中删除该值,然后再次将数组设置为chrome.storage
var theList = result['urlList'];
// Checks if the url that will be deleted is in the array:
if (theList.includes(theUrl)) {
// create a new array without url
var newUrlList = arr.filter(function(item) {
return item !== theUrl;
});
// set new url list to the storage
chrome.storage.sync.set({ 'urlList': newUrlList });
chrome.runtime.reload();
}
你的解释很有道理。一旦我将“arr.filter”更改为“theList.filter”,您的解决方案就运行得非常好。非常感谢。你的解释很有道理。一旦我将“arr.filter”更改为“theList.filter”,您的解决方案就运行得非常好。非常感谢。