浏览器快捷键指南_快速但完整的IndexedDB指南以及在浏览器中存储数据

浏览器快捷键指南

Interested in learning JavaScript? Get my JavaScript ebook at jshandbook.com

有兴趣学习JavaScript吗? 在jshandbook.com上获取我JavaScript电子书

IndexedDB简介 (Introduction to IndexedDB)

IndexedDB is one of the storage capabilities introduced into browsers over the years. It's a key/value store (a noSQL database) considered to be the definitive solution for storing data in browsers.

IndexedDB是多年来浏览器引入的存储功能之一。 它是键/值存储(noSQL数据库),被认为是在浏览器中存储数据的最终解决方案

It's an asynchronous API, which means that performing costly operations won't block the UI thread providing a sloppy experience to users. It can store an indefinite amount of data, although once over a certain threshold the user is prompted to give the site higher limits.

这是一个异步API,这意味着执行昂贵的操作不会阻止UI线程,从而为用户提供草率的体验。 它可以存储无限量的数据,尽管一旦超过某个阈值,系统会提示用户为站点提供更高的限制。

It's supported on all modern browsers.

所有现代浏览器均支持该功能 。

It supports transactions, versioning and gives good performance.

它支持事务,版本控制并提供良好的性能。

Inside the browser we can also use:

在浏览器内部,我们还可以使用:

  • Cookies: can host a very small amount of strings

    Cookies :可以容纳很少量的字符串

  • Web Storage (or DOM Storage), a term that commonly identifies localStorage and sessionStorage, two key/value stores. sessionStorage, does not retain data, which is cleared when the session ends, while localStorage keeps the data across sessions

    Web存储 (或DOM存储),一个通常标识localStorage和sessionStorage这两个键/值存储的术语。 sessionStorage不保留数据,该数据在会话结束时被清除,而localStorage在会话之间保留数据

Local/session storage have the disadvantage of being capped at a small (and inconsistent) size, with browsers implementation offering from 2MB to 10MB of space per site.

本地/会话存储的缺点是限制在较小(且不一致)的大小,每个站点的浏览器实现提供2MB到10MB的空间。

In the past we also had Web SQL, a wrapper around SQLite, but now this is deprecated and unsupported on some modern browsers, it's never been a recognized standard and so it should not be used, although 83% of users have this technology on their devices according to Can I Use.

过去我们也有Web SQL ,它是围绕SQLite的包装,但是现在已经不推荐使用,并且在某些现代浏览器中不支持此包装,尽管它有83%的用户在其上使用了此技术,但它从未被公认是标准,因此不应该使用它。 根据我可以使用的设备 。

While you can technically create multiple databases per site, you generally create one single database, and inside that database you can create multiple object stores.

从技术上讲,每个站点可以创建多个数据库,但是通常可以创建一个数据库 ,并且可以在该数据库内部创建多个对象存储

A database is private to a domain, so any other site cannot access another website IndexedDB stores.

数据库是域专用的 ,因此任何其他站点都无法访问其他网站IndexedDB存储。

Each store usually contains a set of things, which can be

每个商店通常包含一组东西 ,可以是

  • strings

  • numbers

    数字
  • objects

    对象
  • arrays

    数组
  • dates

    日期

For example you might have a store that contains posts, another that contains comments.

例如,您可能有一个包含帖子的商店,另一个包含评论的商店。

A store contains a number of items which have a unique key, which represents the way by which an object can be identified.

商店包含许多具有唯一密钥的项目,该唯一密钥表示识别对象的方式。

You can alter those stores using transactions, by performing add, edit and delete operations, and iterating over the items they contain.

您可以通过执行添加,编辑和删除操作,以及遍历它们包含的项目来使用事务来更改这些商店。

Since the advent of Promises in ES6, and the subsequent move of APIs to using promises, the IndexedDB API seems a bit old school.

自从ES6中Promises的问世以及API后来转向使用Promise以来,IndexedDB API似乎有点老套了

While there's nothing wrong in it, in all the examples that I'll explain I'll use the IndexedDB Promised Library by Jake Archibald, which is a tiny layer on top of the IndexedDB API to make it easier to use.

尽管没有什么错,但在所有要解释的示例中,我将使用Jake Archibald 编写的IndexedDB Promised Library ,它是IndexedDB API之上的一小层,使它易于使用。

This library is also used on all the examples on the Google Developers website regarding IndexedDB

该库还用于Google Developers网站上有关IndexedDB的所有示例中

创建一个IndexedDB数据库 (Create an IndexedDB Database)

The simplest way is to use unpkg, by adding this to the page header:

最简单的方法是使用unpkg ,方法是将其添加到页面标题中:

<script type="module">
import { openDB, deleteDB } from 'https://unpkg.com/idb?module'
</script>

Before using the IndexedDB API, always make sure you check for support in the browser, even though it's widely available, you never know which browser the user is using:

在使用IndexedDB API之前,请务必确保检查浏览器是否提供支持,即使该支持广泛可用,也永远不会知道用户使用的是哪种浏览器:

(() => {'use strict'if (!('indexedDB' in window)) {console.warn('IndexedDB not supported')return}//...IndexedDB code
})()

如何建立资料库 (How to create a database)

Using openDB():

使用openDB()

(async () => {//...const dbName = 'mydbname'const storeName = 'store1'const version = 1 //versions start at 1const db = await openDB(dbName, version, {upgrade(db, oldVersion, newVersion, transaction) {const store = db.createObjectStore(storeName)}})
})()

The first 2 parameters are the database name, and the verson. The third param, which is optional, is an object that contains a function called only if the version number is higher than the current installed database version. In the function body you can upgrade the structure (stores and indexes) of the db.

前两个参数是数据库名称和版本。 第三个参数是可选的,它是一个对象,其中包含仅当版本号高于当前已安装的数据库版本时才调用的函数。 在功能主体中,您可以升级数据库的结构(存储和索引)。

将数据添加到存储中 (Adding data into a store)

创建商店时添加数据,对其进行初始化 (Adding data when the store is created, initializing it)

You use the put method of the object store, but first we need a reference to it, which we can get from db.createObjectStore() when we create it.

您使用对象存储的put方法,但是首先我们需要对其进行引用,我们可以在创建它时从db.createObjectStore()获取它。

When using put, the value is the first argument, the key is the second. This is because if you specify keyPath when creating the object store, you don't need to enter the key name on every put() request, you can just write the value.

使用put ,值是第一个参数,键是第二个参数。 这是因为,如果在创建对象存储库时指定keyPath ,则无需在每个put()请求中都输入键名,只需编写该值即可。

This populates store0 as soon as we create it:

我们创建后立即填充store0

(async () => {//...const dbName = 'mydbname'const storeName = 'store0'const version = 1const db = await openDB(dbName, version,{upgrade(db, oldVersion, newVersion, transaction) {const store = db.createObjectStore(storeName)store.put('Hello world!', 'Hello')}})
})()

使用事务在创建商店后添加数据 (Adding data when the store is already created, using transactions)

To add items later down the road, you need to create a read/write transaction, that ensures database integrity (if an operation fails, all the operations in the transaction are rolled back and the state goes back to a known state).

要在以后添加项目,您需要创建一个读/写事务 ,以确保数据库完整性(如果操作失败,则事务中的所有操作都会回滚,并且状态返回到已知状态)。

For that, use a reference to the dbPromise object we got when calling openDB, and run:

为此,请使用对调用openDB时获得的dbPromise对象的引用,然后运行:

(async () => {//...const dbName = 'mydbname'const storeName = 'store0'const version = 1const db = await openDB(/* ... */)const tx = db.transaction(storeName, 'readwrite')const store = await tx.objectStore(storeName)const val = 'hey!'const key = 'Hello again'const value = await store.put(val, key)await tx.done
})()

从商店获取数据 (Getting data from a store)

从商店获取一件商品: get() (Getting one item from a store: get())

const key = 'Hello again'
const item = await db.transaction(storeName).objectStore(storeName).get(key)

从商店获取所有商品: getAll() (Getting all the items from a store: getAll())

Get all the keys stored

获取所有存储的密钥

const items = await db.transaction(storeName).objectStore(storeName).getAllKeys()

Get all the values stored

获取所有存储的值

const items = await db.transaction(storeName).objectStore(storeName).getAll()

从IndexedDB删除数据 (Deleting data from IndexedDB)

Deleting the database, an object store and data

删除数据库,对象存储和数据

删除整个IndexedDB数据库 (Delete an entire IndexedDB database)

const dbName = 'mydbname'
await deleteDB(dbName)

删除对象存储中的数据 (To delete data in an object store)

We use a transaction:

我们使用一笔交易:

(async () => {//...const dbName = 'mydbname'const storeName = 'store1'const version = 1const db = await openDB(dbName, version, {upgrade(db, oldVersion, newVersion, transaction) {const store = db.createObjectStore(storeName)}})const tx = await db.transaction(storeName, 'readwrite')const store = await tx.objectStore(storeName)const key = 'Hello again'await store.delete(key)await tx.done
})()

从先前版本的数据库迁移 (Migrate from previous version of a database)

The third (optional) parameter of the openDB() function is an object that can contain an upgrade function called only if the version number is higher than the current installed database version. In that function body you can upgrade the structure (stores and indexes) of the db:

openDB()函数的第三个(可选)参数是一个对象,该对象可以包含仅当版本号高于当前已安装的数据库版本时才调用upgrade函数。 在该函数体中,您可以升级数据库的结构(存储和索引):

const name = 'mydbname'
const version = 1
openDB(name, version, {upgrade(db, oldVersion, newVersion, transaction) {console.log(oldVersion)}
})

In this callback, you can check from which version the user is updating, and perform some operations accordingly.

在此回调中,您可以检查用户从哪个版本更新,并相应地执行一些操作。

You can perform a migration from a previous database version using this syntax

您可以使用以下语法从以前的数据库版本执行迁移

(async () => {//...const dbName = 'mydbname'const storeName = 'store0'const version = 1const db = await openDB(dbName, version, {upgrade(db, oldVersion, newVersion, transaction) {switch (oldVersion) {case 0: // no db created before// a store introduced in version 1db.createObjectStore('store1')case 1:// a new store in version 2db.createObjectStore('store2', { keyPath: 'name' })}db.createObjectStore(storeName)}})
})()

唯一键 (Unique keys)

createObjectStore() as you can see in case 1 accepts a second parameter that indicates the index key of the database. This is very useful when you store objects: put() calls don't need a second parameter, but can just take the value (an object) and the key will be mapped to the object property that has that name.

case 1所示, createObjectStore()接受第二个参数,该参数指示数据库的索引键。 这在存储对象时非常有用: put()调用不需要第二个参数,而只需获取值(一个对象),并且键将映射到具有该名称的对象属性。

The index gives you a way to retrieve a value later by that specific key, and it must be unique (every item must have a different key)

索引为您提供了稍后通过​​该特定键检索值的方法,并且该索引必须唯一(每个项目必须具有不同的键)

A key can be set to auto increment, so you don't need to keep track of it on the client code:

可以将键设置为自动递增,因此您无需在客户端代码上跟踪它:

db.createObjectStore('notes', { autoIncrement: true })

Use auto increment if your values do not contain a unique key already (for example, if you collect email addresses without an associated name).

如果您的值尚未包含唯一键(例如,如果您收集的电子邮件地址没有关联的名称),请使用自动递增。

检查商店是否存在 (Check if a store exists)

You can check if an object store already exists by calling the objectStoreNames() method:

您可以通过调用objectStoreNames()方法来检查对象存储是否已存在:

const storeName = 'store1'if (!db.objectStoreNames.contains(storeName)) {db.createObjectStore(storeName)
}

从IndexedDB删除 (Deleting from IndexedDB)

Deleting the database, an object store and data

删除数据库,对象存储和数据

删除数据库 (Delete a database)

await deleteDB('mydb')

删除对象库 (Delete an object store)

An object store can only be deleted in the callback when opening a db, and that callback is only called if you specify a version higher than the one currently installed:

仅在打开数据库时才能在回调中删除对象存储,并且仅当您指定的版本高于当前安装的版本时,才调用该回调:

const db = await openDB('dogsdb', 2, {upgrade(db, oldVersion, newVersion, transaction) {switch (oldVersion) {case 0: // no db created before// a store introduced in version 1db.createObjectStore('store1')case 1:// delete the old store in version 2, create a new onedb.deleteObjectStore('store1')db.createObjectStore('store2')}}
})

要删除对象存储中的数据,请使用事务 (To delete data in an object store use a transaction)

const key = 232 //a random keyconst db = await openDB(/*...*/)
const tx = await db.transaction('store', 'readwrite')
const store = await tx.objectStore('store')
await store.delete(key)
await tx.complete

还有更多! (There's more!)

These are just the basics. I didn't talk about cursors and more advanced stuff. There's more to IndexedDB but I hope this gives you a head start.

这些只是基础知识。 我没有谈论游标和更高级的内容。 IndexedDB还有更多功能,但我希望这能为您提供一个开端。

Interested in learning JavaScript? Get my JavaScript book at jshandbook.com

有兴趣学习JavaScript吗? 在jshandbook.com上获取我JavaScript书

翻译自: https://www.freecodecamp.org/news/a-quick-but-complete-guide-to-indexeddb-25f030425501/

浏览器快捷键指南

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391663.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java-Character String StringBuffer StringBuilder

Java Character 类 Character 类用于对单个字符进行操作character 类在对象包装一个基本类型char的值 char ch "a";char uniChar \u039A;char[] charArray {a, b, c};使用Character的构造方法创建一个Character类对象 Character ch new Character(a);Charact…

已知两点坐标拾取怎么操作_已知的操作员学习-第3部分

已知两点坐标拾取怎么操作有关深层学习的FAU讲义 (FAU LECTURE NOTES ON DEEP LEARNING) These are the lecture notes for FAU’s YouTube Lecture “Deep Learning”. This is a full transcript of the lecture video & matching slides. We hope, you enjoy this as mu…

缺失值和异常值处理

一、缺失值 1.空值判断 isnull()空值为True&#xff0c;非空值为False notnull() 空值为False&#xff0c;非空值为True s pd.Series([1,2,3,np.nan,hello,np.nan]) df pd.DataFrame({a:[1,2,np.nan,3],b:[2,np.nan,3,hello]}) print(s.isnull()) print(s[s.isnull() False]…

leetcode 503. 下一个更大元素 II(单调栈)

给定一个循环数组&#xff08;最后一个元素的下一个元素是数组的第一个元素&#xff09;&#xff0c;输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序&#xff0c;这个数字之后的第一个比它更大的数&#xff0c;这意味着你应该循环地搜索它的下一个更…

setNeedsDisplay看我就懂!

前言&#xff1a; setNeedsDisplay异步执行的。它会自动调用drawRect方法&#xff0c;这样可以拿到 UIGraphicsGetCurrentContext&#xff0c;就可以绘制了。而setNeedsLayout会默认调用layoutSubViews&#xff0c;处理子视图中的一些数据。 一、着手 我定义了一个UIView的子类…

如何使用ArchUnit测试Java项目的体系结构

by Emre Savcı由EmreSavcı 如何使用ArchUnit测试Java项目的体系结构 (How to test your Java project’s architecture with ArchUnit) In this post, I will show you an interesting library called ArchUnit that I met recently. It does not test your code flow or bu…

解决ionic3 android 运行出现Application Error - The connection to the server was unsuccessful

在真机上启动ionic3打包成的android APK,启动了很久结果弹出这个问题&#xff1a; Application Error - The connection to the server was unsuccessful 可能是我项目资源太多东西了&#xff0c;启动的时间太久了&#xff0c;导致超时了。 解决方案是在项目目录下的config.xml…

特征工程之特征选择_特征工程与特征选择

特征工程之特征选择&#x1f4c8;Python金融系列 (&#x1f4c8;Python for finance series) Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you.警告 &#xff1a; 这里没有神奇的配方或圣杯&#xff0c;尽管新世界可…

搭建Harbor企业级docker仓库

https://www.cnblogs.com/pangguoping/p/7650014.html 转载于:https://www.cnblogs.com/gcgc/p/11377461.html

leetcode 131. 分割回文串(dp+回溯)

给你一个字符串 s&#xff0c;请你将 s 分割成一些子串&#xff0c;使每个子串都是 回文串 。返回 s 所有可能的分割方案。 回文串 是正着读和反着读都一样的字符串。 示例 1&#xff1a; 输入&#xff1a;s “aab” 输出&#xff1a;[[“a”,“a”,“b”],[“aa”,“b”]]…

[翻译练习] 对视图控制器压入导航栈进行测试

译自&#xff1a;swiftandpainless.com/testing-pus… 上个月我写的关于使用 Swift 进行测试驱动开发的书终于出版了&#xff0c;我会在本文和接下来的一些博文中介绍这本书撰写过程中的一些心得和体会。 在本文中&#xff0c;我将会展示一种很好的用来测试一个视图控制器是否因…

python多人游戏服务器_Python在线多人游戏开发教程

python多人游戏服务器This Python online game tutorial from Tech with Tim will show you how to code a scaleable multiplayer game with python using sockets/networking and pygame. You will learn how to deploy your game so that people anywhere around the world …

版本号控制-GitHub

前面几篇文章。我们介绍了Git的基本使用方法及Gitserver的搭建。本篇文章来学习一下怎样使用GitHub。GitHub是开源的代码库以及版本号控制库&#xff0c;是眼下使用网络上使用最为广泛的服务&#xff0c;GitHub能够托管各种Git库。首先我们须要注冊一个GitHub账号&#xff0c;打…

leetcode132. 分割回文串 II(dp)

给你一个字符串 s&#xff0c;请你将 s 分割成一些子串&#xff0c;使每个子串都是回文。 返回符合要求的 最少分割次数 。 示例 1&#xff1a; 输入&#xff1a;s “aab” 输出&#xff1a;1 解释&#xff1a;只需一次分割就可将 s 分割成 [“aa”,“b”] 这样两个回文子串…

数据标准化和离散化

在某些比较和评价的指标处理中经常需要去除数据的单位限制&#xff0c;将其转化为无量纲的纯数值&#xff0c;便于不同单位或量级的指标能够进行比较和加权。因此需要通过一定的方法进行数据标准化&#xff0c;将数据按比例缩放&#xff0c;使之落入一个小的特定区间。 一、标准…

熊猫tv新功能介绍_熊猫简单介绍

熊猫tv新功能介绍Out of all technologies that is introduced in Data Analysis, Pandas is one of the most popular and widely used library.在Data Analysis引入的所有技术中&#xff0c;P andas是最受欢迎和使用最广泛的库之一。 So what are we going to cover :那么我…

关于sublime-text-2的Package Control组件安装方法,自动和手动

之前在自己的文章《Linux下安装以及破解sublim-text-2编辑器》的文章中提到过关于sublime-text-2的Package Control组件安装方法。 当时使用的是粘贴代码&#xff1a; 1import urllib2,os;pfPackage Control.sublime-package;ippsublime.installed_packages_path();os.makedirs…

上海区块链会议演讲ppt_进行第一次会议演讲的完整指南

上海区块链会议演讲pptConferences can be stressful even if you are not giving a talk. On the other hand, speaking can really boost your career, help you network, allow you to travel for (almost) free, and give back to others at the same time.即使您不讲话…

windows下Call to undefined function curl_init() error问题

本地项目中使用到curl_init()时出现Call to undefined function curl_init()的错误&#xff0c;去掉php.ini中的extensionphp_curl.dll前的分号还是不行&#xff0c;phpinfo()中无curl模块&#xff0c;于是上网搜索并实践了如下方法&#xff0c;成功&#xff1a; 在使用php5的c…

数据转换软件_数据转换

数据转换软件&#x1f4c8;Python金融系列 (&#x1f4c8;Python for finance series) Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you.警告 &#xff1a;这里没有神奇的配方或圣杯&#xff0c;尽管新世界可能为您…