[英]Remove variables starting with a string from chrome.storage.local in JavaScript
在chrome擴展程序中,我將一些變量存儲在chrome.storage.local中,如下所示: chrome.storage.local.set({["name" + counter]: ""}, function() {});
(非常感謝克桑的關於ES6計算的屬性名稱的答案在這里 ),其中counter
基本上是一個遞增的編號。
當我不再需要它們時,如何使用chrome.storage.local.remove
刪除所有以“ name”開頭的變量。
注意:我使用這種類型的存儲(“ name0”,“ name1”,...),因為我無法將它們存儲為數組,無法在chrome.storage.local
中chrome.storage.local
更新(我必須先獲取數組,對其進行更新,然后將其存儲回去,這不適用於大量數據。 另外,在執行新擴展時,我不知道最大counter
值,因此無法在for
循環中使用它。
由於事情超出了我的能力范圍,因此我嘗試對此發表評論。 但是,由於這給出了正確的格式,因此。
我查看了chrome.storage
,如果將null
傳遞給第一個參數,則將獲得整個值。 因此,通過提供回調,它變為
chrome.storage.local.get(null, function (items) {
for (var key in items) {
if (key.startsWith('name')) { // or key.includes or whatever
chrome.storage.local.remove(key)
}
}
})
由於存儲的項目可能足夠大,因此也許可以將密鑰存儲在另一個密鑰名稱中。 包裝函數示例
function set(key, value) {
var collectionOfKeys = chrome.storage.local.get('collection_of_keys') || []
collection_of_keys.push(key)
chrome.storage.local.set('collection_of_keys', collection_of_keys)
chrome.storage.local.set('name' + key, value)
}
去除
chrome.storage.local.remove(chrome.storage.local.get('collection_of_keys'))
好吧,如果鍵的大小仍然很大,那就足夠傻了。
如果您按順序保持它,也許可以跟蹤它的長度。
function set(key, value) {
var collectionOfKeyLength = chrome.storage.local.get('collection_of_key_length') || 0
chrome.storage.local.set('collection_of_key_length', collectionOfKeyLength + 1)
chrome.storage.local.set('name' + key, value)
}
function remove () {
for (var i = 0; i < chrome.storage.local.get('collection_of_key_length'); i++) {
chrome.storage.local.remove('name' + i)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.