IndexedDB:您可以使用数组元素作为键或索引吗?

IndexedDB: Can you use an array element as a key or an index?

考虑以下对象存储,domain 键设置为 keyPath

var tags  = [ 
    //codes: 0 - markdown wrap tag
    //       1 - HTML wrap tag 
    //       2 - single tag
    { domain: "youtube", 

      bold:["*",0],
      strikethrough:["-",0],
      italic:["_",0] 
    },  


    { domain: "Whosebug", 

      bold:["<strong>",1], 
      italic:["<em>",1],
      strikethrough:["<del>",1],
      superscript:["<sup>",1],
      subscript:["<sub>",1],
      heading1:["<h1>",1],
      heading2:["<h2>",1],
      heading3:["<h3>",1],
      blockquote:["<blockquote>",1],
      code:["<code>",1],
      newline:["<br>",2],
      horizontal:["<hr>",2]
    }   
];  

上面的代码工作正常,让我可以轻松高效地进行查找。但是,在很多情况下,store 中的两个对象除了 domain 属性之外完全相同。

例如,我想将所有 Stack Exchange 站点的对象添加到商店中,并且所有这些对象都等于 Whosebug 的对象。

因此,我不想创建许多单独的对象,而是想做这样的事情:

var tags  = [ 
    //codes: 0 - markdown wrap tag
    //       1 - HTML wrap tag 
    //       2 - single tag
    { domain: ["youtube"], 

      bold:["*",0],
      strikethrough:["-",0],
      italic:["_",0] 
    },  


    { domain: ["Whosebug","stackexchange",...], 

      bold:["<strong>",1], 
      italic:["<em>",1],
      strikethrough:["<del>",1],
      superscript:["<sup>",1],
      subscript:["<sub>",1],
      heading1:["<h1>",1],
      heading2:["<h2>",1],
      heading3:["<h3>",1],
      blockquote:["<blockquote>",1],
      code:["<code>",1],
      newline:["<br>",2],
      horizontal:["<hr>",2]
    }   
];  

是否可以使用 KeyGen 而不是 keyPath 并设置某种索引,获取一个值并在 [=12 指向的数组中搜索它=] 键?

或者我每次要查找时都必须使用游标吗?

一些可能有用的参考资料是:

解决方案是使用 multiEntry 键 属性 设置为 true

的索引

参见this link(感谢@kyaw Tun)

Each index also has a multiEntry flag. This flag affects how the index behaves when the result of evaluating the index's key path yields an Array. If the multiEntry flag is false, then a single record whose key is an Array is added to the index. If the multiEntry flag is true, then the one record is added to the index for each item in the Array. The key for each record is the value of respective item in the Array.

有了这个 index,不再需要特定的 keyPath,因此您可以使用 keyGen 来简单起见。


因此,要创建数据库:

request.onupgradeneeded = function(event) 
{
   var db = event.target.result;
   var objectStore = db.createObjectStore("domains", {autoIncrement: true });
   objectStore.createIndex("domain", "domain", { unique: true, multiEntry: true });
   for(var i in tags)
   {
       objectStore.add(tags[i]);
       console.log("added " + tags[i]["domain"] + " to the DB");
   }
};  

以及使用域查询对象的示例:

    var objectStore = db.transaction("domains").objectStore("domains");
    var query = objectStore.index("domain").get(queryURL);
    query.onsuccess = function(event){...};