首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何循环访问IndexedDB中的存储键

如何循环访问IndexedDB中的存储键
EN

Stack Overflow用户
提问于 2018-04-12 16:03:27
回答 2查看 1K关注 0票数 0

我正在为IndexedDB使用localForage,我需要遍历存储键,但不是全部。我只需要遍历以名称"field-“开头的键。例如: field-1,field-2,field-3,...

EN

回答 2

Stack Overflow用户

发布于 2018-05-22 01:24:31

从我发现的情况来看,不可能获得存储中的所有可用密钥。但是,由于您在某个时刻设置了localforage的所有键,也许您可以单独存储这些键。

代码语言:javascript
复制
// 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)
  })

这样做之后,您就可以使用它来迭代所有可用的键

代码语言:javascript
复制
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函数单独存储子集

代码语言:javascript
复制
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)
  })
票数 0
EN

Stack Overflow用户

发布于 2019-04-03 20:18:18

代码语言:javascript
复制
localforage.iterate(function(value, key, iterationNumber) {
  if (key.indexOf("field-") > -1) {
    // do something
  }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49791101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档