0

我将 localForage 用于 IndexedDB,我需要遍历存储键,但不是全部。我只需要遍历以名称“field-”开头的键。例如:字段 1、字段 2、字段 3、...

4

2 回答 2

0

根据我的发现,不可能获得存储中的所有可用密钥。但是由于您在某个时候设置了 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
    })
  })

因为您不想遍历所有键,您可以再次使用过滤器函数单独存储子集

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)
  })
于 2018-05-21T17:24:31.230 回答
0
localforage.iterate(function(value, key, iterationNumber) {
  if (key.indexOf("field-") > -1) {
    // do something
  }
});
于 2019-04-03T12:18:17.710 回答