IndexedDB的IDBCursor中key和primaryKey之间的区别是什么

时间:2016-06-22 14:31:26

标签: javascript indexeddb

documentation here says that

  

返回光标的当前键。 (游标还有一个键和一个值,表示最后一个迭代记录的键和值。)

的PrimaryKey

  

返回光标的当前有效密钥。 (如果光标源是对象存储,则光标的有效对象存储是该对象存储,光标的有效键是光标的位置。)

在下面的示例中,两者使用完全相同,我得到两个相同的值:

那么实际的区别是什么?

1 个答案:

答案 0 :(得分:5)

如果您在对象存储上进行迭代,则它们是相同的。

如果要迭代索引,key索引键primaryKey对象库中的键。

例如:

 book_store = db.createObjectStore('books');
 title_index = store.createIndex('by_title', 'title');

 key = 123;
 value = {title: 'IDB for Newbies', author: 'Alice'};
 book_store.put(value, key);

 book_store.openCursor().onsuccess = function(e) {
   cursor = e.target.result;
   console.log(cursor.key); // logs 123
   console.log(cursor.primaryKey); // logs 123
 };
 title_index.openCursor().onsuccess = function(e) {
   cursor = e.target.result;
   console.log(cursor.key); // logs 'IDB for Newbies'
   console.log(cursor.primaryKey); // logs 123
 };