最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What's the difference between key and primaryKey in IDBCursor of IndexedDB - Stack Overflow

programmeradmin1浏览0评论

The documentation here says that

key

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.)

primaryKey

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.)

In the examples below however the two are used exactly the same and I get the same values for both:

So what is the practical difference?

The documentation here says that

key

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.)

primaryKey

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.)

In the examples below however the two are used exactly the same and I get the same values for both:

  • https://developer.mozilla/en-US/docs/Web/API/IDBCursor/primaryKey
  • https://developer.mozilla/en-US/docs/Web/API/IDBCursor/key

So what is the practical difference?

Share Improve this question edited Jun 22, 2016 at 14:47 uberlaufer asked Jun 22, 2016 at 14:31 uberlauferuberlaufer 2612 silver badges8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

If you're iterating over an object store, they are the same.

If you are iterating over an index, the key is the index key and the primaryKey is the key in the object store.

For example:

 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
 };
发布评论

评论列表(0)

  1. 暂无评论