IndexedDB的IDBCursor中key和primaryKey有什么区别

What's the difference between key and primaryKey in IDBCursor of IndexedDB

documentation here says that

关键

Returns the cursor's current key. (Cursors also have a key and a value which represent the key and the value of the last iterated record.)

主键

Returns the cursor's current effective key. (If the source of a cursor is an object store, the effective object store of the cursor is that object store and the effective key of the cursor is the cursor's position.)

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

那么实际区别是什么?

如果您遍历对象存储,它们是相同的。

如果您正在遍历索引,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
 };