localStorage和indexedDB区别

localStorage和indexedDB区别

前言

两者都是在客户端存储数据,可以存储较多数据,且都是永久性保存。

不同点

  • indexedDB是JS脚本语言可以操作的数据库
  • 操作是异步的
  • IndexedDB 支持事务(transaction),这意味着一系列操作步骤之中,只要有一步失败,整个事务就都取消,数据库回滚到事务发生之前的状态,不存在只改写一部分数据的情况。
  • 储存空间大 IndexedDB 的储存空间比 LocalStorage 大得多,一般来说不少于 250MB,甚至没有上限。
  • LocalStorage 不支持搜索。

相同点

  • 可以在客户端存储永久性数据
  • 都通过键值对存储数据
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,这是一种获取浏览器不变的唯一标识符的方法。具体实现可以参考以下代码: ```javascript // 生成一个随机的唯一标识符 function generateUUID() { var d = new Date().getTime(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); return uuid; } // 检查浏览器是否支持localStorageIndexedDB function isLocalStorageSupported() { try { var testKey = 'test'; var storage = window.localStorage; storage.setItem(testKey, '1'); storage.removeItem(testKey); return true; } catch (error) { return false; } } function isIndexedDBSupported() { return 'indexedDB' in window; } // 从localStorageIndexedDB中读取唯一标识符 function getUniqueID() { var uniqueID = ''; if (isLocalStorageSupported()) { var storage = window.localStorage; uniqueID = storage.getItem('uniqueID'); if (!uniqueID) { uniqueID = generateUUID(); storage.setItem('uniqueID', uniqueID); } } else if (isIndexedDBSupported()) { var request = window.indexedDB.open('uniqueID', 1); request.onerror = function(event) { console.log('Failed to open indexedDB'); }; request.onupgradeneeded = function(event) { var db = event.target.result; var objectStore = db.createObjectStore('uniqueID', { keyPath: 'id' }); var uniqueID = generateUUID(); objectStore.add({ id: 1, value: uniqueID }); }; request.onsuccess = function(event) { var db = event.target.result; var transaction = db.transaction(['uniqueID'], 'readwrite'); var objectStore = transaction.objectStore('uniqueID'); var getRequest = objectStore.get(1); getRequest.onsuccess = function(event) { if (getRequest.result) { uniqueID = getRequest.result.value; } else { uniqueID = generateUUID(); objectStore.add({ id: 1, value: uniqueID }); } }; }; } else { uniqueID = generateUUID(); } return uniqueID; } ``` 以上代码中,`generateUUID()`函数用于生成一个随机的唯一标识符,`isLocalStorageSupported()`和`isIndexedDBSupported()`函数用于检查浏览器是否支持localStorageIndexedDB,`getUniqueID()`函数用于从localStorageIndexedDB中读取唯一标识符,如果没有则生成一个新的唯一标识符并存储到localStorageIndexedDB中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值