我正在为IndexedDB使用localForage,我需要遍历存储键,但不是全部。我只需要遍历以名称"field-“开头的键。例如: field-1,field-2,field-3,...
发布于 2018-05-22 01:24:31
从我发现的情况来看,不可能获得存储中的所有可用密钥。但是,由于您在某个时刻设置了localforage的所有键,也许您可以单独存储这些键。
// storing a new key, could be wrapped inside of a function and included anywhere you update localforage
const newKey = "abc"
const availableKeys = localforage.getItem('keys')
.then((keys = []) => { // localforage will return undefined if the key does not already exists, this will set it do an empty array by default
// check here if key is already in keys (using Array.find)
// push the key that you want to add
keys.push(newKey)
// now update the new keys array in localforage
localforage.setItem('keys', keys)
})这样做之后,您就可以使用它来迭代所有可用的键
localforage.getItem('keys')
.then((keys = []) => {
keys.forEach(key => {
// you could not check if the key has you pattern
if (key.indexOf("field-") > -1) // key has "field-", now do something
})
})由于您不希望遍历所有键,因此可以再次使用filter函数单独存储子集
localforage.getItem('keys')
.then((keys = []) => {
// fiter all keys that match your pattern
const filteredKeys = keys.filter(key => key.indexOf("field-") > -1)
// store filtered keys in localeforage
localforage.setItem("filteredKeys", filteredKeys)
})发布于 2019-04-03 20:18:18
localforage.iterate(function(value, key, iterationNumber) {
if (key.indexOf("field-") > -1) {
// do something
}
});https://stackoverflow.com/questions/49791101
复制相似问题