From 522984283b56b68582d606c76e4ca98c0baf9451 Mon Sep 17 00:00:00 2001 From: MDN Date: Tue, 15 Jun 2021 00:35:40 +0000 Subject: [CRON] sync translated content --- files/de/_redirects.txt | 8 +- files/de/_wikihistory.json | 28 +-- .../basic_concepts_behind_indexeddb/index.html | 195 ++++++++++++++++ .../typed_array_invalid_arguments/index.html | 78 +++++++ .../basic_concepts_behind_indexeddb/index.html | 195 ---------------- .../typed_array_invalid_arguments/index.html | 78 ------- files/es/_redirects.txt | 5 +- files/es/_wikihistory.json | 18 +- .../basic_concepts_behind_indexeddb/index.html | 217 ++++++++++++++++++ .../basic_concepts_behind_indexeddb/index.html | 217 ------------------ files/fr/_redirects.txt | 10 +- files/fr/_wikihistory.json | 34 +-- .../basic_concepts_behind_indexeddb/index.html | 210 +++++++++++++++++ .../typed_array_invalid_arguments/index.html | 77 +++++++ .../basic_concepts_behind_indexeddb/index.html | 210 ----------------- .../typed_array_invalid_arguments/index.html | 77 ------- files/ja/_redirects.txt | 2 + files/ja/_wikihistory.json | 34 +-- .../basic_concepts_behind_indexeddb/index.html | 218 ++++++++++++++++++ .../typed_array_invalid_arguments/index.html | 78 +++++++ .../basic_concepts_behind_indexeddb/index.html | 217 ------------------ .../typed_array_invalid_arguments/index.html | 77 ------- files/ko/_redirects.txt | 3 +- files/ko/_wikihistory.json | 30 +-- .../basic_concepts_behind_indexeddb/index.html | 224 ++++++++++++++++++ .../basic_concepts_behind_indexeddb/index.html | 223 ------------------ files/pt-br/_redirects.txt | 3 +- files/pt-br/_wikihistory.json | 22 +- .../basic_concepts_behind_indexeddb/index.html | 250 +++++++++++++++++++++ .../basic_concepts_behind_indexeddb/index.html | 249 -------------------- files/ru/_redirects.txt | 4 +- files/ru/_wikihistory.json | 32 +-- .../basic_concepts_behind_indexeddb/index.html | 214 ++++++++++++++++++ .../typed_array_invalid_arguments/index.html | 79 +++++++ .../basic_concepts_behind_indexeddb/index.html | 213 ------------------ .../typed_array_invalid_arguments/index.html | 78 ------- files/zh-cn/_redirects.txt | 4 +- files/zh-cn/_wikihistory.json | 56 ++--- .../basic_concepts_behind_indexeddb/index.html | 205 +++++++++++++++++ .../typed_array_invalid_arguments/index.html | 77 +++++++ .../basic_concepts_behind_indexeddb/index.html | 204 ----------------- .../typed_array_invalid_arguments/index.html | 76 ------- files/zh-tw/_redirects.txt | 3 +- files/zh-tw/_wikihistory.json | 20 +- .../basic_concepts_behind_indexeddb/index.html | 210 +++++++++++++++++ .../basic_concepts_behind_indexeddb/index.html | 209 ----------------- 46 files changed, 2497 insertions(+), 2474 deletions(-) create mode 100644 files/de/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/de/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html delete mode 100644 files/de/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html delete mode 100644 files/de/web/javascript/reference/errors/typed_array_invalid_arguments/index.html create mode 100644 files/es/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html delete mode 100644 files/es/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/fr/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/fr/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html delete mode 100644 files/fr/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html delete mode 100644 files/fr/web/javascript/reference/errors/typed_array_invalid_arguments/index.html create mode 100644 files/ja/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/ja/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html delete mode 100644 files/ja/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html delete mode 100644 files/ja/web/javascript/reference/errors/typed_array_invalid_arguments/index.html create mode 100644 files/ko/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html delete mode 100644 files/ko/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/pt-br/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html delete mode 100644 files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/ru/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/ru/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html delete mode 100644 files/ru/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html delete mode 100644 files/ru/web/javascript/reference/errors/typed_array_invalid_arguments/index.html create mode 100644 files/zh-cn/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/zh-cn/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html delete mode 100644 files/zh-cn/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html delete mode 100644 files/zh-cn/web/javascript/reference/errors/typed_array_invalid_arguments/index.html create mode 100644 files/zh-tw/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html delete mode 100644 files/zh-tw/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html diff --git a/files/de/_redirects.txt b/files/de/_redirects.txt index cb41416960..785ace89dc 100644 --- a/files/de/_redirects.txt +++ b/files/de/_redirects.txt @@ -320,7 +320,7 @@ /de/docs/Hauptseite /de/docs/Web /de/docs/IndexedDB /de/docs/Web/API/IndexedDB_API /de/docs/IndexedDB/Browser_storage_limits_and_eviction_criteria /de/docs/Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria -/de/docs/IndexedDB/Grundkonzepte_hinter_IndexedDB /de/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/de/docs/IndexedDB/Grundkonzepte_hinter_IndexedDB /de/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /de/docs/IndexedDB/IndexedDB_verwenden /de/docs/Web/API/IndexedDB_API/Using_IndexedDB /de/docs/JavaScript /de/docs/Web/JavaScript /de/docs/JavaScript/Eine_Wiedereinfuehrung_in_JavaScript /de/docs/Web/JavaScript/A_re-introduction_to_JavaScript @@ -488,7 +488,8 @@ /de/docs/Web/API/Element.querySelector /de/docs/Web/API/Element/querySelector /de/docs/Web/API/File/Typ /de/docs/Web/API/File/type /de/docs/Web/API/File/Zugriff_auf_Dateien_von_Webapplikationen /de/docs/Web/API/File/Using_files_from_web_applications -/de/docs/Web/API/IndexedDB_API/Grundkonzepte_hinter_IndexedDB /de/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/de/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /de/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/de/docs/Web/API/IndexedDB_API/Grundkonzepte_hinter_IndexedDB /de/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /de/docs/Web/API/IndexedDB_API/IndexedDB_verwenden /de/docs/Web/API/IndexedDB_API/Using_IndexedDB /de/docs/Web/API/LinkStyle /de/docs/orphaned/Web/API/LinkStyle /de/docs/Web/API/MozMobileConnection.selectNetworkAutomatically /de/docs/Web/API/MozMobileConnection/selectNetworkAutomatically @@ -736,6 +737,7 @@ /de/docs/Web/JavaScript/Reference/Anweisungen/for...in /de/docs/Web/JavaScript/Reference/Statements/for...in /de/docs/Web/JavaScript/Reference/Anweisungen/let /de/docs/Web/JavaScript/Reference/Statements/let /de/docs/Web/JavaScript/Reference/Anweisungen/var /de/docs/Web/JavaScript/Reference/Statements/var +/de/docs/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /de/docs/orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /de/docs/Web/JavaScript/Reference/Fehler /de/docs/Web/JavaScript/Reference/Errors /de/docs/Web/JavaScript/Reference/Fehler/Already_has_pragma /de/docs/Web/JavaScript/Reference/Errors/Already_has_pragma /de/docs/Web/JavaScript/Reference/Fehler/Array_sort_argument /de/docs/Web/JavaScript/Reference/Errors/Array_sort_argument @@ -802,7 +804,7 @@ /de/docs/Web/JavaScript/Reference/Fehler/Stmt_after_return /de/docs/Web/JavaScript/Reference/Errors/Stmt_after_return /de/docs/Web/JavaScript/Reference/Fehler/Strict_Non_Simple_Params /de/docs/Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params /de/docs/Web/JavaScript/Reference/Fehler/Too_much_recursion /de/docs/Web/JavaScript/Reference/Errors/Too_much_recursion -/de/docs/Web/JavaScript/Reference/Fehler/Typed_array_invalid_arguments /de/docs/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +/de/docs/Web/JavaScript/Reference/Fehler/Typed_array_invalid_arguments /de/docs/orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /de/docs/Web/JavaScript/Reference/Fehler/Undeclared_var /de/docs/Web/JavaScript/Reference/Errors/Undeclared_var /de/docs/Web/JavaScript/Reference/Fehler/Undefined_prop /de/docs/Web/JavaScript/Reference/Errors/Undefined_prop /de/docs/Web/JavaScript/Reference/Fehler/Unexpected_token /de/docs/Web/JavaScript/Reference/Errors/Unexpected_token diff --git a/files/de/_wikihistory.json b/files/de/_wikihistory.json index 36c9948270..05f7a170e9 100644 --- a/files/de/_wikihistory.json +++ b/files/de/_wikihistory.json @@ -3650,14 +3650,6 @@ "Huan" ] }, - "Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { - "modified": "2020-01-13T04:47:55.526Z", - "contributors": [ - "chrisdavidmills", - "gmagholder", - "Julini" - ] - }, "Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria": { "modified": "2020-01-13T04:47:56.415Z", "contributors": [ @@ -10331,12 +10323,6 @@ "akumagamo" ] }, - "Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { - "modified": "2020-03-12T19:47:33.971Z", - "contributors": [ - "schlagi123" - ] - }, "Web/JavaScript/Reference/Errors/Undeclared_var": { "modified": "2020-03-12T19:47:43.541Z", "contributors": [ @@ -14700,6 +14686,14 @@ "sv3m0r" ] }, + "orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { + "modified": "2020-01-13T04:47:55.526Z", + "contributors": [ + "chrisdavidmills", + "gmagholder", + "Julini" + ] + }, "orphaned/Web/API/LinkStyle": { "modified": "2019-03-23T23:11:18.020Z", "contributors": [ @@ -14772,6 +14766,12 @@ "RmnWtnkmp" ] }, + "orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { + "modified": "2020-03-12T19:47:33.971Z", + "contributors": [ + "schlagi123" + ] + }, "orphaned/Web/JavaScript/Reference/Global_Objects/Array/prototype": { "modified": "2020-10-15T21:52:42.525Z", "contributors": [ diff --git a/files/de/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/de/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..ec07174c23 --- /dev/null +++ b/files/de/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,195 @@ +--- +title: Grundkonzepte +slug: orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +original_slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

IndexedDB ermöglicht es Ihnen Daten innerhalb des Browsers eines Benutzers permanent abzulegen. Weil es Sie Webanwendungen mit funktionsreichen Abfragemöglichkeiten erstellen lässt, können diese Anwendungen sowohl online als auch offline funktionieren. IndexedDB ist geeignet für Anwendungen, die eine große Menge an Daten speichern (z.B. ein Katalog von DVDs in einer Videothek) und Anwendungen, die keine durchgehende Internetverbindung benötigen um zu funktionieren (z.B. E-Mail-Clients, To-Do-Listen oder Notizen).

+

Über dieses Dokument

+

Diese Einführung bespricht wesentliche Konzepte und Fachbegriffe in IndexedDB. Sie liefert Ihnen einen Gesamtüberblick und führt Sie in die Schlüsselkonzepte ein. Um mehr über die Begrifflichkeiten von IndexedDB zu erfahren, lesen Sie den Abschnitt Definitionen.

+

Eine Anleitung zur Verwendung der API finden Sie im Artikel Using IndexedDB. Eine Referenzdokumentierung der IndexedDB-API finden Sie im Artikel IndexedDB und dessen Unterseiten, welche die Objekttypen dokumentiert, die von IndexedDB verwendet werden, ebenso wie die Methoden von synchronen wie asynchronen APIs.

+

Überblick über IndexedDB

+

Mit IndexedDB lassen sich indizierte Objekte mit „Schlüsseln“ ablegen und abrufen. Alle Änderungen an der Datenbank geschehen innerhalb von Transaktionen. Wie die meisten Webspeicher-Lösungen folgt IndexedDB einer Same-Origin-Policy. Während also auf Daten, die innerhalb einer Domain gespeichert wurden, zugegriffen werden kann, kann nicht domainübergreifend auf Daten zugegriffen werden.

+

Die API umfasst sowohl eine asynchrone API als auch eine synchrone API. Die asynchrone API kann für die meisten Fälle verwendet werden, auch für WebWorkers, während die synchrone API nur für den Gebrauch durch WebWorkers gedacht ist. Momentan wird die synchrone API von keinem der großen Browser unterstützt. Aber selbst wenn synchrone APIs unterstützt wären, würden Sie eher die asynchrone API verwenden, wenn Sie mit IndexedDB arbeiten.

+

IndexedDB ist eine Alternative zur WebSQL-Datenbank, welche vom W3C am 18. November 2010 als veraltet erklärt wurde. Während sowohl IndexedDB als auch WebSQL Lösungen zur Speicherung von Daten bieten, bieten sie nicht dieselben Funktionalitäten. WebSQL-Datenbank ist ein relationales Datenbankanfragesystem, IndexedDB hingegen ist ein indiziertes Tabellensystem.

+

Wichtige Konzepte

+

Wenn Sie die Arbeit mit anderen Datenbanksystemen gewohnt sind kann die Arbeit mit IndexedDB am Anfang ungewohnt erscheinen. Behalten Sie deshalb folgende wichtige Konzepte im Hinterkopf:

+ +

Definitionen

+

Dieser Abschitt definiert und erklärt Begriffe, die in der IndexedDB-API verwendet werden.

+

Datenbank

+
+
+ Datenbank
+
+ Ein Aufbewahrungsort für Informationen, typischerweise bestehend aus einem oder mehreren Objektspeichern. Jede Datenbank muss folgende Angaben enthalten: +
    +
  • Name. Er identifiziert die Datenbank innerhalb einer konkreten Herkunft und verändert sich nicht innerhalb seiner Lebenszeit. Der Name kann aus einem beliebigen String-Wert bestehen (einschließlich dem leeren String).
  • +
  • +

    Aktuelle Version. Wenn eine Datenbank zum ersten Mal erstellt wird, nimmt ihre Version den integer-Wert 1 an, wenn nichts anderes angegeben wird. Jede Datenbank kann zu einem Zeitpunkt nur eine Version haben.

    +
  • +
+
+
+ Objektspeicher
+
+

Das Instrument, mit welchem Daten in einer Datenbank gespeichert werden. Der Objektspeicher hält Eintragungen aus Schlüssel-Wert-Paaren permanent. Eintragungen innerhalb eines Objektspeichers werden entsprechend der Schlüssel in aufsteigender Reihenfolge sortiert.

+

Jeder Objektspeicher muss einen Namen haben, der innerhalb seiner Datenbank einzigartig ist. Der Objektspeicher kann optional einen Schlüsselerzeuger und einen Schlüsselpfad besitzen. Wenn der Objektspeicher einen Schlüsselpfad hat, verwendet er in-line keys; ansonsten out-of-line keys.

+

Eine Referenzdokumentation zu Objektspeichern finden Sie unter IDBObjectStore oder IDBObjectStoreSync.

+
+
+ Version
+
+ Wenn eine Datenbank zum ersten Mal erstellt wird, ist ihre Versionsnummer die integer-Zahl 1. Jede Datenbank hat zu jedem Zeitpunkt genau eine Versionsnummer; eine Datenbank kann nicht in verschiedenen Versionen gleichzeitig existieren. Die Versionsnummer kann nur geändert werden, indem die Datenbank mit einer größeren Versionsnummer geöffnet wird als mit der aktuellen. Das wird die Transaktion versionchange starten und ein upgradeneeded Ereignis auslösen. Die einzige Stelle, an der das Schema der Datenbank geupdatet werden kann, ist innerhalb des Handlers dieses Ereignisses.
+  
+
+ Anmerkung: Diese Definition beschreibt die aktuellsten Spezifikationen, welche nur in Browsern auf dem neuesten Stand implementiert sind. In alten Browsern ist die mittlerweile veraltete und entfernte Methode IDBDatabase.setVersion() implementiert.
+
+ Datenbankverbindung
+
+ Eine Operation, die beim Öffnen einer Datenbank erstellt wird. Eine vorgegebene Datenbank kann mehrere Verbindungen gleichzeitig haben.
+
+ Transaktion
+
+

Eine nicht teilbare und dauerhafte Menge an Datenzugriffs- und Datenmodifikationsoperationen auf einer bestimmten Datenbank. Durch Transaktionen können Sie auf die Daten einer Datenbank zugreifen. Tatsächlich muss jeder Lese- oder Schreibvorgang von Daten in einer Transaktion stattfinden.
+
+ Eine Datenbankverbindung kann mit mehreren aktiven Transaktionen gleichzeitig verknüpft sein, so lange schreibende Transaktionen keine überlappenden scopes haben. The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the flyingMonkey object store, you can start a second transaction with a scope of the unicornCentaur and unicornPegasus object stores. As for reading transactions, you can have several of them—even overlapping ones.

+

Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.

+

The three modes of transactions are: readwrite, readonly, and versionchange. The only way to create and delete object stores and indexes is by using a versionchange transaction. To learn more about transaction types, see the reference article for IndexedDB.

+

Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see IDBTransaction, which also has reference documentation. For the documentation on the synchronous API, see IDBTransactionSync.

+
+
+ Anfrage
+
+ Die Operation, mit der Lese- und Schreibvorgänge auf einer Datenbank ausgeführt werden. Jede Anfrage repräsentiert eine Lese- oder Schreiboperation.
+
+ Index
+
+

Ein Spezialobjektspeicher zum Nachschlagen von Einträgen eines anderen Objektspeichers, bezeichnet als referenzierter Objektspeicher. Der Index ist ein persistenter Schlüssel-Wert-Speicher, wobei der Wert seiner Einträge dem Schlüssel eines Eintrages im referenzierten Objektspeicher entspricht. Die Einträge in einem Index werden automatisch eingepflegt, sobald Einträge im referenzierten Objekt eingefügt, aktualisiert oder entfernt werden. Jeder Eintrag in einem Index kann auf nur einen Eintrag in seinem referenzierten Objektspeicher zeigen, aber mehrere Indizes können auf denselben Objektspeicher verweisen. Wenn der Objektspeicher sich ändert, werden alle Indizes, die auf ihn verweisen, automatisch aktualisiert.

+

Alternativ können Einträge eines Objektspeichers mithilfe eines Schlüssels nachgeschlagen werden.

+

Um mehr über die Verwendung von Indizes zu erfahren, lesen Sie Using IndexedDB. Die Referenzdokumentation zu Indizes finden Sie unter IDBKeyRange.

+
+
+

Schlüssel und Wert

+
+
+ Schlüssel
+
+

Ein Datenwert über welchen abgelegte Werte aus dem Objektspeicher sortiert und ausgelesen werden können. Der Objektspeicher kann den Schlüssel aus einer dieser drei Quellen erlangen: Einem Schlüsselgenerator, einem Schlüsselpfad und einem explizit angegebem Wert. Der Schlüssel muss aus einem Datentyp bestehen, der eine Nummer hat, die größer ist als die des Schlüssel vor ihm. Jeder Eintrag in einem Objektspeicher muss einen innerhalb des gleichen Objektspeichers einzigartigen Schlüssel haben, deshalb können nicht mehrere Einträge mit demselben Schlüssel in einem vorgegebenem Objektspeicher vorliegen.
+
+ Ein Schlüssel kann einen der folgenden Typen haben: string, date, float und array. Bei Arrays kann der Schlüssel zwischen einem leeren Wert und unendlich liegen. Arrays können wiederum Arrays beinhalten. Es gibt keine Vorschrift nur Schlüssel der Typen string oder integer zu verwenden.

+

Alternativ können Sie Einträge eines Objektspeichers auch mithilfe eines Index nachschlagen.

+
+
+ Schlüsselgenerator
+
+ Ein Mechanismus um neue Schlüssel in einer angeordneten Reihenfolge zu erzeugen. Wenn ein Objektspeicher über keinen Schlüsselgenerator verfügt, muss die Anwendung Schlüssel für zu speichernde Einträge zur Verfügung stellen. Generatoren werden nicht zwischen Speichern geteilt. Dies ist mehr ein Detail von Browserimplementierungen, da in der Webentwicklung nicht wirklich Schlüsselgeneratoren erzeugt oder auf sie zugegriffen wird.
+
+ in-line key
+
+ A key that is stored as part of the stored value. It is found using a key path. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
+
+ out-of-line key
+
+ A key that is stored separately from the value being stored.
+
+ key path
+
+ Defines where the browser should extract the key from a value in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods. It cannot include spaces.
+
+ value
+
+

Each record has a value, which could include anything that can be expressed in JavaScript, including: boolean, number, string, date, object, array, regexp, undefined, and null.

+

When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.

+

Blobs and files can be stored, cf. specification.

+
+
+

Range and scope

+
+
+ scope
+
+ The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
+
+ cursor
+
+ A mechanism for iterating over multiple records with a key range. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see IDBCursor or IDBCursorSync.
+
+ key range
+
+

A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.

+

For the reference documentation on key range, see IDBKeyRange.

+
+
+

Limitations

+

IndexedDB is designed to cover most cases that need client-side storage. However, it is not designed for a few cases like the following:

+ +

In addition, be aware that browsers can wipe out the database, such as in the following conditions:

+ +

The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible.

+
+

Warning: At the moment due to bugs or on purpose it's impossible to open an IndexedDB database from a Web App. This needs more investigation and then be documented.

+
+

Next step

+

OK, so, now with these big concepts under our belts, we can get to more concrete stuff. For a tutorial on how to use the API, see Using IndexedDB.

+

See also

+

Specification

+ +

Reference

+ +

Tutorials

+ +

Related article

+ diff --git a/files/de/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/de/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html new file mode 100644 index 0000000000..7d379b7a5b --- /dev/null +++ b/files/de/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html @@ -0,0 +1,78 @@ +--- +title: 'TypeError: invalid arguments' +slug: orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +tags: + - Error + - Errors + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +original_slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +--- +
{{jsSidebar("Errors")}}
+ +

Fehlermeldung

+ +
TypeError: invalid arguments (Firefox)
+ +

Fehlertyp

+ +

{{jsxref("TypeError")}}

+ +

Was ist falsch gelaufen?

+ +

Der Typed Array Konstruktor erwartet entweder

+ + + +

um ein neues Typed Array zu erstelltn. Andere Argumente im Konstruktor erstellen kein valides Typed Array.

+ +

Beispiele

+ +

Typed Arrays, zum Beispiel ein {{jsxref("Uint8Array")}}, können nicht von einem String erstellt werden. Tatsächlich können String nicht in typisierten Arrays enthalten sein.

+ +
var ta = new Uint8Array("nope");
+// TypeError: invalid arguments
+
+ +

Verschiedene Wege um ein valides {{jsxref("Uint8Array")}} Objekt zu erstellen:

+ +
// From a length
+var uint8 = new Uint8Array(2);
+uint8[0] = 42;
+console.log(uint8[0]); // 42
+console.log(uint8.length); // 2
+console.log(uint8.BYTES_PER_ELEMENT); // 1
+
+// From an array
+var arr = new Uint8Array([21,31]);
+console.log(arr[1]); // 31
+
+// From another TypedArray
+var x = new Uint8Array([21, 31]);
+var y = new Uint8Array(x);
+console.log(y[0]); // 21
+
+// From an ArrayBuffer
+var buffer = new ArrayBuffer(8);
+var z = new Uint8Array(buffer, 1, 4);
+
+// From an iterable
+var iterable = function*(){ yield* [1,2,3]; }();
+var uint8 = new Uint8Array(iterable);
+// Uint8Array[1, 2, 3]
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/de/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html deleted file mode 100644 index 7eac56fb64..0000000000 --- a/files/de/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: Grundkonzepte -slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -original_slug: Web/API/IndexedDB_API/Grundkonzepte_hinter_IndexedDB ---- -

IndexedDB ermöglicht es Ihnen Daten innerhalb des Browsers eines Benutzers permanent abzulegen. Weil es Sie Webanwendungen mit funktionsreichen Abfragemöglichkeiten erstellen lässt, können diese Anwendungen sowohl online als auch offline funktionieren. IndexedDB ist geeignet für Anwendungen, die eine große Menge an Daten speichern (z.B. ein Katalog von DVDs in einer Videothek) und Anwendungen, die keine durchgehende Internetverbindung benötigen um zu funktionieren (z.B. E-Mail-Clients, To-Do-Listen oder Notizen).

-

Über dieses Dokument

-

Diese Einführung bespricht wesentliche Konzepte und Fachbegriffe in IndexedDB. Sie liefert Ihnen einen Gesamtüberblick und führt Sie in die Schlüsselkonzepte ein. Um mehr über die Begrifflichkeiten von IndexedDB zu erfahren, lesen Sie den Abschnitt Definitionen.

-

Eine Anleitung zur Verwendung der API finden Sie im Artikel Using IndexedDB. Eine Referenzdokumentierung der IndexedDB-API finden Sie im Artikel IndexedDB und dessen Unterseiten, welche die Objekttypen dokumentiert, die von IndexedDB verwendet werden, ebenso wie die Methoden von synchronen wie asynchronen APIs.

-

Überblick über IndexedDB

-

Mit IndexedDB lassen sich indizierte Objekte mit „Schlüsseln“ ablegen und abrufen. Alle Änderungen an der Datenbank geschehen innerhalb von Transaktionen. Wie die meisten Webspeicher-Lösungen folgt IndexedDB einer Same-Origin-Policy. Während also auf Daten, die innerhalb einer Domain gespeichert wurden, zugegriffen werden kann, kann nicht domainübergreifend auf Daten zugegriffen werden.

-

Die API umfasst sowohl eine asynchrone API als auch eine synchrone API. Die asynchrone API kann für die meisten Fälle verwendet werden, auch für WebWorkers, während die synchrone API nur für den Gebrauch durch WebWorkers gedacht ist. Momentan wird die synchrone API von keinem der großen Browser unterstützt. Aber selbst wenn synchrone APIs unterstützt wären, würden Sie eher die asynchrone API verwenden, wenn Sie mit IndexedDB arbeiten.

-

IndexedDB ist eine Alternative zur WebSQL-Datenbank, welche vom W3C am 18. November 2010 als veraltet erklärt wurde. Während sowohl IndexedDB als auch WebSQL Lösungen zur Speicherung von Daten bieten, bieten sie nicht dieselben Funktionalitäten. WebSQL-Datenbank ist ein relationales Datenbankanfragesystem, IndexedDB hingegen ist ein indiziertes Tabellensystem.

-

Wichtige Konzepte

-

Wenn Sie die Arbeit mit anderen Datenbanksystemen gewohnt sind kann die Arbeit mit IndexedDB am Anfang ungewohnt erscheinen. Behalten Sie deshalb folgende wichtige Konzepte im Hinterkopf:

- -

Definitionen

-

Dieser Abschitt definiert und erklärt Begriffe, die in der IndexedDB-API verwendet werden.

-

Datenbank

-
-
- Datenbank
-
- Ein Aufbewahrungsort für Informationen, typischerweise bestehend aus einem oder mehreren Objektspeichern. Jede Datenbank muss folgende Angaben enthalten: -
    -
  • Name. Er identifiziert die Datenbank innerhalb einer konkreten Herkunft und verändert sich nicht innerhalb seiner Lebenszeit. Der Name kann aus einem beliebigen String-Wert bestehen (einschließlich dem leeren String).
  • -
  • -

    Aktuelle Version. Wenn eine Datenbank zum ersten Mal erstellt wird, nimmt ihre Version den integer-Wert 1 an, wenn nichts anderes angegeben wird. Jede Datenbank kann zu einem Zeitpunkt nur eine Version haben.

    -
  • -
-
-
- Objektspeicher
-
-

Das Instrument, mit welchem Daten in einer Datenbank gespeichert werden. Der Objektspeicher hält Eintragungen aus Schlüssel-Wert-Paaren permanent. Eintragungen innerhalb eines Objektspeichers werden entsprechend der Schlüssel in aufsteigender Reihenfolge sortiert.

-

Jeder Objektspeicher muss einen Namen haben, der innerhalb seiner Datenbank einzigartig ist. Der Objektspeicher kann optional einen Schlüsselerzeuger und einen Schlüsselpfad besitzen. Wenn der Objektspeicher einen Schlüsselpfad hat, verwendet er in-line keys; ansonsten out-of-line keys.

-

Eine Referenzdokumentation zu Objektspeichern finden Sie unter IDBObjectStore oder IDBObjectStoreSync.

-
-
- Version
-
- Wenn eine Datenbank zum ersten Mal erstellt wird, ist ihre Versionsnummer die integer-Zahl 1. Jede Datenbank hat zu jedem Zeitpunkt genau eine Versionsnummer; eine Datenbank kann nicht in verschiedenen Versionen gleichzeitig existieren. Die Versionsnummer kann nur geändert werden, indem die Datenbank mit einer größeren Versionsnummer geöffnet wird als mit der aktuellen. Das wird die Transaktion versionchange starten und ein upgradeneeded Ereignis auslösen. Die einzige Stelle, an der das Schema der Datenbank geupdatet werden kann, ist innerhalb des Handlers dieses Ereignisses.
-  
-
- Anmerkung: Diese Definition beschreibt die aktuellsten Spezifikationen, welche nur in Browsern auf dem neuesten Stand implementiert sind. In alten Browsern ist die mittlerweile veraltete und entfernte Methode IDBDatabase.setVersion() implementiert.
-
- Datenbankverbindung
-
- Eine Operation, die beim Öffnen einer Datenbank erstellt wird. Eine vorgegebene Datenbank kann mehrere Verbindungen gleichzeitig haben.
-
- Transaktion
-
-

Eine nicht teilbare und dauerhafte Menge an Datenzugriffs- und Datenmodifikationsoperationen auf einer bestimmten Datenbank. Durch Transaktionen können Sie auf die Daten einer Datenbank zugreifen. Tatsächlich muss jeder Lese- oder Schreibvorgang von Daten in einer Transaktion stattfinden.
-
- Eine Datenbankverbindung kann mit mehreren aktiven Transaktionen gleichzeitig verknüpft sein, so lange schreibende Transaktionen keine überlappenden scopes haben. The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the flyingMonkey object store, you can start a second transaction with a scope of the unicornCentaur and unicornPegasus object stores. As for reading transactions, you can have several of them—even overlapping ones.

-

Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.

-

The three modes of transactions are: readwrite, readonly, and versionchange. The only way to create and delete object stores and indexes is by using a versionchange transaction. To learn more about transaction types, see the reference article for IndexedDB.

-

Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see IDBTransaction, which also has reference documentation. For the documentation on the synchronous API, see IDBTransactionSync.

-
-
- Anfrage
-
- Die Operation, mit der Lese- und Schreibvorgänge auf einer Datenbank ausgeführt werden. Jede Anfrage repräsentiert eine Lese- oder Schreiboperation.
-
- Index
-
-

Ein Spezialobjektspeicher zum Nachschlagen von Einträgen eines anderen Objektspeichers, bezeichnet als referenzierter Objektspeicher. Der Index ist ein persistenter Schlüssel-Wert-Speicher, wobei der Wert seiner Einträge dem Schlüssel eines Eintrages im referenzierten Objektspeicher entspricht. Die Einträge in einem Index werden automatisch eingepflegt, sobald Einträge im referenzierten Objekt eingefügt, aktualisiert oder entfernt werden. Jeder Eintrag in einem Index kann auf nur einen Eintrag in seinem referenzierten Objektspeicher zeigen, aber mehrere Indizes können auf denselben Objektspeicher verweisen. Wenn der Objektspeicher sich ändert, werden alle Indizes, die auf ihn verweisen, automatisch aktualisiert.

-

Alternativ können Einträge eines Objektspeichers mithilfe eines Schlüssels nachgeschlagen werden.

-

Um mehr über die Verwendung von Indizes zu erfahren, lesen Sie Using IndexedDB. Die Referenzdokumentation zu Indizes finden Sie unter IDBKeyRange.

-
-
-

Schlüssel und Wert

-
-
- Schlüssel
-
-

Ein Datenwert über welchen abgelegte Werte aus dem Objektspeicher sortiert und ausgelesen werden können. Der Objektspeicher kann den Schlüssel aus einer dieser drei Quellen erlangen: Einem Schlüsselgenerator, einem Schlüsselpfad und einem explizit angegebem Wert. Der Schlüssel muss aus einem Datentyp bestehen, der eine Nummer hat, die größer ist als die des Schlüssel vor ihm. Jeder Eintrag in einem Objektspeicher muss einen innerhalb des gleichen Objektspeichers einzigartigen Schlüssel haben, deshalb können nicht mehrere Einträge mit demselben Schlüssel in einem vorgegebenem Objektspeicher vorliegen.
-
- Ein Schlüssel kann einen der folgenden Typen haben: string, date, float und array. Bei Arrays kann der Schlüssel zwischen einem leeren Wert und unendlich liegen. Arrays können wiederum Arrays beinhalten. Es gibt keine Vorschrift nur Schlüssel der Typen string oder integer zu verwenden.

-

Alternativ können Sie Einträge eines Objektspeichers auch mithilfe eines Index nachschlagen.

-
-
- Schlüsselgenerator
-
- Ein Mechanismus um neue Schlüssel in einer angeordneten Reihenfolge zu erzeugen. Wenn ein Objektspeicher über keinen Schlüsselgenerator verfügt, muss die Anwendung Schlüssel für zu speichernde Einträge zur Verfügung stellen. Generatoren werden nicht zwischen Speichern geteilt. Dies ist mehr ein Detail von Browserimplementierungen, da in der Webentwicklung nicht wirklich Schlüsselgeneratoren erzeugt oder auf sie zugegriffen wird.
-
- in-line key
-
- A key that is stored as part of the stored value. It is found using a key path. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
-
- out-of-line key
-
- A key that is stored separately from the value being stored.
-
- key path
-
- Defines where the browser should extract the key from a value in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods. It cannot include spaces.
-
- value
-
-

Each record has a value, which could include anything that can be expressed in JavaScript, including: boolean, number, string, date, object, array, regexp, undefined, and null.

-

When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.

-

Blobs and files can be stored, cf. specification.

-
-
-

Range and scope

-
-
- scope
-
- The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
-
- cursor
-
- A mechanism for iterating over multiple records with a key range. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see IDBCursor or IDBCursorSync.
-
- key range
-
-

A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.

-

For the reference documentation on key range, see IDBKeyRange.

-
-
-

Limitations

-

IndexedDB is designed to cover most cases that need client-side storage. However, it is not designed for a few cases like the following:

- -

In addition, be aware that browsers can wipe out the database, such as in the following conditions:

- -

The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible.

-
-

Warning: At the moment due to bugs or on purpose it's impossible to open an IndexedDB database from a Web App. This needs more investigation and then be documented.

-
-

Next step

-

OK, so, now with these big concepts under our belts, we can get to more concrete stuff. For a tutorial on how to use the API, see Using IndexedDB.

-

See also

-

Specification

- -

Reference

- -

Tutorials

- -

Related article

- diff --git a/files/de/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/de/web/javascript/reference/errors/typed_array_invalid_arguments/index.html deleted file mode 100644 index b6621776e6..0000000000 --- a/files/de/web/javascript/reference/errors/typed_array_invalid_arguments/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: 'TypeError: invalid arguments' -slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments -tags: - - Error - - Errors - - JavaScript - - TypeError -translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments -original_slug: Web/JavaScript/Reference/Fehler/Typed_array_invalid_arguments ---- -
{{jsSidebar("Errors")}}
- -

Fehlermeldung

- -
TypeError: invalid arguments (Firefox)
- -

Fehlertyp

- -

{{jsxref("TypeError")}}

- -

Was ist falsch gelaufen?

- -

Der Typed Array Konstruktor erwartet entweder

- - - -

um ein neues Typed Array zu erstelltn. Andere Argumente im Konstruktor erstellen kein valides Typed Array.

- -

Beispiele

- -

Typed Arrays, zum Beispiel ein {{jsxref("Uint8Array")}}, können nicht von einem String erstellt werden. Tatsächlich können String nicht in typisierten Arrays enthalten sein.

- -
var ta = new Uint8Array("nope");
-// TypeError: invalid arguments
-
- -

Verschiedene Wege um ein valides {{jsxref("Uint8Array")}} Objekt zu erstellen:

- -
// From a length
-var uint8 = new Uint8Array(2);
-uint8[0] = 42;
-console.log(uint8[0]); // 42
-console.log(uint8.length); // 2
-console.log(uint8.BYTES_PER_ELEMENT); // 1
-
-// From an array
-var arr = new Uint8Array([21,31]);
-console.log(arr[1]); // 31
-
-// From another TypedArray
-var x = new Uint8Array([21, 31]);
-var y = new Uint8Array(x);
-console.log(y[0]); // 21
-
-// From an ArrayBuffer
-var buffer = new ArrayBuffer(8);
-var z = new Uint8Array(buffer, 1, 4);
-
-// From an iterable
-var iterable = function*(){ yield* [1,2,3]; }();
-var uint8 = new Uint8Array(iterable);
-// Uint8Array[1, 2, 3]
-
- -

Siehe auch

- - diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 2c483adb18..1d5953075f 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -986,7 +986,7 @@ /es/docs/Incrustando_Mozilla/Comunidad /es/docs/orphaned/Incrustando_Mozilla/Comunidad /es/docs/IndexedDB /es/docs/conflicting/Web/API/IndexedDB_API /es/docs/IndexedDB-840092-dup /es/docs/Web/API/IndexedDB_API -/es/docs/IndexedDB-840092-dup/Conceptos_Basicos_Detras_De_IndexedDB /es/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/es/docs/IndexedDB-840092-dup/Conceptos_Basicos_Detras_De_IndexedDB /es/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /es/docs/IndexedDB-840092-dup/Usando_IndexedDB /es/docs/Web/API/IndexedDB_API/Using_IndexedDB /es/docs/Instalación_de_motores_de_búsqueda_desde_páginas_web /es/docs/orphaned/Instalación_de_motores_de_búsqueda_desde_páginas_web /es/docs/Instalar_el_manifest /es/docs/Manifiesto_de_instalación @@ -1817,7 +1817,8 @@ /es/docs/Web/API/HTMLElement/invalid_event /es/docs/Web/API/HTMLInputElement/invalid_event /es/docs/Web/API/HTMLElement/style /es/docs/orphaned/Web/API/ElementCSSInlineStyle/style /es/docs/Web/API/IDBObjectStore.add /es/docs/Web/API/IDBObjectStore/add -/es/docs/Web/API/IndexedDB_API/Conceptos_Basicos_Detras_De_IndexedDB /es/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/es/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /es/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/es/docs/Web/API/IndexedDB_API/Conceptos_Basicos_Detras_De_IndexedDB /es/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /es/docs/Web/API/IndexedDB_API/Usando_IndexedDB /es/docs/Web/API/IndexedDB_API/Using_IndexedDB /es/docs/Web/API/Navigator.getUserMedia /es/docs/Web/API/Navigator/getUserMedia /es/docs/Web/API/NavigatorGeolocation /es/docs/conflicting/Web/API/Geolocation diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index ee60191d01..f1b37b448d 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -7784,15 +7784,6 @@ "MPoli" ] }, - "Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { - "modified": "2020-01-13T04:48:11.759Z", - "contributors": [ - "chrisdavidmills", - "fscholz", - "elin3t", - "sebasmagri" - ] - }, "Web/API/IndexedDB_API/Using_IndexedDB": { "modified": "2020-01-13T04:48:12.209Z", "contributors": [ @@ -23407,6 +23398,15 @@ "HenryGR" ] }, + "orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { + "modified": "2020-01-13T04:48:11.759Z", + "contributors": [ + "chrisdavidmills", + "fscholz", + "elin3t", + "sebasmagri" + ] + }, "orphaned/Web/API/ParentNode": { "modified": "2019-03-23T22:43:20.773Z", "contributors": [ diff --git a/files/es/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/es/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..81bfcf5693 --- /dev/null +++ b/files/es/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,217 @@ +--- +title: Conceptos Básicos +slug: orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +original_slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

IndexedDB es una manera de almacenar datos de manera persistente en el navegador. Dado que permite la creación de aplicaciones web con capacidades de consulta mejoradas, éstas pueden funcionar tanto en línea como fuera de línea. IndexedDB es útil para aplicaciones que almacenan una gran cantidad de datos (catálogos de DVDs en una biblioteca, por ejemplo) y para aplicaciones que no necesitan de una conexión permanente a internet para funcionar (clientes de correo, listas de tareas y blocs de notas, por ejemplo).

+ +

Sobre este documento

+ +

Esta introducción discute conceptos y terminologías fundamentales en IndexedDB. Provee una visión general y orienta sobre los conceptos clave. Para aprender más sobre los términos relacionados con IndexedDB, vea la sección de Definiciones.

+ +

Para un tutorial sobre cómo usar la API, vea Usando IndexedDB. Para ver la documentación de referencia sobre la API de IndexedDB, vea el artículo IndexedDB y sus sub-páginas, que documentan los tipos de objetos utilizados por IndexedDB, así como los métodos de las API síncrona y asíncrona.

+ +

Visión general de IndexedDB

+ +

IndexedDB le permite almacenar y obtener objetos indizados a partir de una "llave". Todos los cambios realizados a la base de datos ocurren dentro de transacciones. Como la mayoría de las soluciones de almacenamiento web, IndexedDB sigue una política de mismo origen, por lo que aún cuando se puede acceder a datos almacenados en un dominio, no se pueden acceder a datos a través de distintos dominios.

+ +

La API incluye una variante asíncrona y una síncrona. La variante asíncrona puede ser utilizada en la mayoría de los casos, incluyendo WebWorkers, mientras la variante síncrona está diseñada para ser utilizada solo con WebWorkers. Actualmente, ninguno de los navegadores principales soportan la API síncrona. Sin embargo, aún cuando la API síncrona sea soportada, en la mayoría de los casos de uso de IndexedDB lo más probable es que se utilice la API asíncrona.

+ +

IndexedDB es una alternativa a WebSQL, que fue marcada como obsoleta por W3C el 18 de Noviembre de 2010. Aún cuando IndexedDB y WebSQL son soluciones para el almacenamiento, éstas no ofrecen las mismas funcionalidades. WebSQL es un sistema relacional de acceso a datos, mientras que IndexedDB es un sistema de tablas indizadas.

+ +

Conceptos principales

+ +

Si usted tiene alguna idea de cómo trabajan otros tipos de bases de datos, podría tener algún conflicto de conceptos al trabajar con IndexedDB. Por esta razón mantenga los siguientes conceptos importantes en mente:

+ + + +

Definiciones

+ +

Esta sección define y explica los términos utilizados en la API de IndexedDB.

+ +

Base de Datos

+ +
+
base de datos
+
Un repositorio de información, típicamente compuesto de uno o más  almacenes de objetos. Cada base de datos debe tener: +
    +
  • Nombre. Identifica la base de datos dentro de un mismo origen y no cambia a lo largo de la existencia de ésta. El nombre puede ser cualquier cadena de caracteres (incluyendo una vacía).
  • +
  • +

    Versión actual. Cuando una base de datos se crea por primera vez, la versión es el número entero 1 si no se indica otra cosa. Cada base de datos puede tener una y sólo una versión en cualquier momento.

    +
  • +
+
+
almacén de objetos
+
+

El mecanismo a través del cual los datos son almacenados en la base de datos. El almacén de objetos mantiene registros de manera persistente, que son pares de llave-valor. Los registros dentro de un almacén de objetos son ordenados de acuerdo con las llaves en orden ascendente.

+ +

Todo almacén de objetos debe tener un nombre que es único a lo largo de su base de datos. Opcionalmente puede tener un generador de llaves y una ruta de llaves. Si el almacén tiene una ruta de llaves, éste utiliza llaves en línea; si no, utiliza llaves fuera de línea.

+ +

Para documentación de referencia sobre los almacenes de objetos, vew IDBObjectStore o IDBObjectStoreSync.

+
+
versión
+
Cuando una base de datos es creada por primera vez, su versión es 1. Cada base de datos tiene una versión en cualquier momento y no puede tener varias versiones al mismo tiempo. La única manera de cambiar la versión es abrir la base de datos con una versión mayor a la actual. Esto arranca una transacción versionchange y dispara el evento upgradeneeded. El único momento cuando se puede actualizar el esquema de la base de datos es dentro del manejador de este evento.
+
Nota: Esta definición describe la especificación más actual, que solo está implementada por las versiones más nuevas de los navegadores. Los navegadores más antiguos implementaron el método IDBDatabase.setVersion(), que ya ha sido marcado obsoleto y removido.
+
conexión a la base de datos
+
Una operación creada al abrir una base de datos. Una base de datos puede tener múltiples conexiónes al mismo tiempo.
+
transacción
+
+

Un conjunto atómico y durable de operaciónes de acceso y modificación de datos sobre una base de datos particular. Esta es la manera cómo se interactúa con los datos de una base de datos. De hecho, cualquier lectura o modificación de datos en la base de datos debe ocurrir dentro de una transacción.

+ +

Una conexión a la base de datos puede tener varias transacciones activas, siempre que las operaciones de escrituras no tengan ámbitos que se solapen. El ámbito de las transacciones, que es definido al momento en que éstas son creadas, determina con qué almacenes de datos puede interactuar ésta y permanece constante a lo largo de su existencia. Así, por ejemplo, si una conexión tiene una transacción escribiendo con un ámbito que abarca solo el almacén flyingMonkey, se puede iniciar una segunda que tenga como ámbito los almacenes unicornCentaur y unicornPegasus. En el caso de las transacciones de lectura, se pueden tener varias aún cuando se solapen.

+ +

Se espera que las transacciones tengan una existencia corta, de manera que el navegador puede cancelar una transacción que tome demasiado tiempo para liberar recursos que la misma tenga bloqueados. Usted puede abortar la transacción, lo que deshace los cambios hechos a la base de datos durante la misma. Ni siquiera es necesario esperar a que la transacción inicie para abortarla.

+ +

Los tres modos de transacción son: readwrite, readonly, y versionchange. La única manera de crear y borrar almacenes es usar una transacción versionchange. Para aprender más sobre los tipos de transacción, vea al artículo de referencia de IndexedDB.

+ +

Debido a que todo sucede dentro de una transacción, este es un concepto muy importante. Para aprender más sobre las transacciones, especialmente sobre como se relacionan con el versionado, vea IDBTransaction, que también cuenta con documentación de referencia. Para la documentación sobre la API asíncrona, vea IDBTransactionSync.

+
+
solicitud
+
La operación por medio de la cual se lee o se escribe en una base de datos. Toda solicitud representa una y solo una operación de lectura o escritura.
+
índice
+
+

Un almacén especializado para buscar registros en otro almacén, llamado almacén de objetos referenciado. El índice es un almacenamiento persistente llave-valor donde el valor es una llave del almacén referenciado. Los registros en un índice son rellenados automáticamente cada vez que se modifican los registros del almacén referenciado. Cada registro en un índice puede apuntar solo a un registro de su almacén referenciado, pero varios índices pueden apuntar al mismo almacén.

+ +

Alternativamente, se pueden realizar búsquedas en un almacén de objetos usando la llave.

+ +

Para aprender más sobre el uso de los índices, vea Usando IndexedDB. Para documentación de referencia, vea IDBKeyRange.

+
+
+ +

Llave y valor

+ +
+
llave
+
+

Es uno de los atributos del objeto a partir del cual los demás objetos son organizados y obtenidos desde el almacén de objetos. El almacén puede derivar una llave desde uno de tres orígenes: un generador de llaves, una ruta de llave, y un valor indicado de forma explícita. La llave debe ser de un tipo de datos que tenga un número creciente en relación con los objetos almacenados previamente. Cada registro en un almacén de datos debe tener una llave única en el almacén, de manera que no se pueden tener varios objetos con la misma llave en un almacén de objetos dado.

+ + +

Una llave puede ser de uno de los siguientes tipos: String, Date, float, y Array. Para los arreglos, la llave puede tener un rango desde un valor vacío hasta infinito, y puede incluirse un arreglo dentro de otro. No se requiere usar solo cadenas o enteros para las llaves.

+ +

Como alternativa, se pueden realizar búsquedas de objetos usando un índice.

+
+
generador de llaves
+
Es un mecanismo para producir nuevas llaves en una secuencia ordenada. Si un almacén de objetos no tiene un generador de llaves, entonces la aplicación debe proveer llaves para los registros que se almacenen. Los generadores no son compartidos entre almacenes. Esto es un detalle de implementación de los navegadores, porque en desarrollo web, realmente no se crea o se accede a un generador de llaves.
+
llaves en línea
+
Es una llave que se almacena como parte del valor almacenado. La manera como se determina cuál es la llave es utilizando una  ruta de llave. Una llave en línea puede obtenerse con un generador. Después de que la llave ha sido generada, esta puede almacenarse en el valor usando la ruta del atributo o puede ser usada directamente como llave.
+
llave fuera de línea
+
Una llave que se almacena separada del valor.
+
ruta de llave
+
Define de dónde se debe extraer la llave desde un valor en el almacén o en un índice. Una ruta de llave válida puede incluir alguno de los siguientes: una cadena vacía, un identificador de JavaScript, o múltiples identificadores de JavaScript separados con puntos. No puede incluir espacios.
+
valor
+
+

Cada registro tiene un valor, el cual puede ser cualquier cosa que pueda ser expresada en JavaScript, incluyendo: booleanos, números, cadenas, fechas, objetos, arreglos, expresiones regulares, undefined, y null.

+ +

Cuando un objeto o un arreglo es almacenado, las propiedades y valores en ese objeto o arreglo pueden ser cualquier cosa que sea un valor válido.

+ +

Se pueden almacenar Blobs y archivos. cf. especificación.

+
+
+ +

Rango y ámbito

+ +
+
ámbito
+
El conjunto de almacenes de objetos e índices en los que una transacción aplica. Los ámbitos de varias transacciones de solo lectura pueden solaparse y ejecutarse al mismo tiempo. En cambio, los ámbitos de transacciones de escritura no pueden solaparse. Aún así se pueden crear varias transacciones con el mismo ámbito al mismo tiempo, pero éstas serán manejadas por una cola y ejecutadas una detrás de otra.
+
cursor
+
Un mecanismo para iterar a través de múltiples registros con un rango de llaves. El cursor tiene un orígen que indica que índice o almacén de datos está iterando. El cursor tiene una posición dentro del rango, y se mueve en dirección creciente o decreciente en el orden de las llaves de cada registro. Para obtener documentación de referencia sobre cursores, vea IDBCursor o IDBCursorSync.
+
rango de llaves
+
+

Un intervalo continuo sobre algún tipo de datos utilizado para las llaves. Los registros pueden obtenerse desde los almacenes e índices usando llaves o un rango de llaves. Los rangos pueden limitarse o filtrarse con umbrales inferiores y superiores. Por ejemplo, se puede iterar sobre todos los valores de una llave desde x hasta y.

+ +

Para documentación de referencia sobre los rangos de llaves, vea IDBKeyRange.

+
+
+ +

Limitaciones

+ +

IndexedDB está diseñado para cubrir la mayoría de los casos en los que se necesita almacenamiento del lado del cliente. Sin embargo, no están contemplados en su diseño unos pocos casos como los siguientes:

+ + + +

Adicionalmente, tenga en cuenta que los navegadores podrían eliminar la base de datos, como en las siguientes condiciones:

+ + + +

Las circunstancias exactas y capacidades de los navegadores cambian con el tiempo, pero la filosofía de los navegadores es, en general, hacer lo posible por conservar los datos.

+ +
+

Advertencia: Al momento, debido a errores o a propósito, es imposible abrir una base de datos IndexedDB desde un Web App. Esto requiere mayor investigación para documentarlo.

+
+ +

Próximo paso

+ +

Ok, ahora con estos conceptos generales bajo nuestros cinturones, podemos seguir a cosas más concretas. Para un tutorial sobre como utilizar la API, vea Usando IndexedDB.

+ +

Vea también

+ +

Especificación

+ + + +

Referencia

+ + + +

Tutoriales

+ + + +

Artículo relacionado

+ + diff --git a/files/es/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/es/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html deleted file mode 100644 index 5fb145939d..0000000000 --- a/files/es/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html +++ /dev/null @@ -1,217 +0,0 @@ ---- -title: Conceptos Básicos -slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -original_slug: Web/API/IndexedDB_API/Conceptos_Basicos_Detras_De_IndexedDB ---- -

IndexedDB es una manera de almacenar datos de manera persistente en el navegador. Dado que permite la creación de aplicaciones web con capacidades de consulta mejoradas, éstas pueden funcionar tanto en línea como fuera de línea. IndexedDB es útil para aplicaciones que almacenan una gran cantidad de datos (catálogos de DVDs en una biblioteca, por ejemplo) y para aplicaciones que no necesitan de una conexión permanente a internet para funcionar (clientes de correo, listas de tareas y blocs de notas, por ejemplo).

- -

Sobre este documento

- -

Esta introducción discute conceptos y terminologías fundamentales en IndexedDB. Provee una visión general y orienta sobre los conceptos clave. Para aprender más sobre los términos relacionados con IndexedDB, vea la sección de Definiciones.

- -

Para un tutorial sobre cómo usar la API, vea Usando IndexedDB. Para ver la documentación de referencia sobre la API de IndexedDB, vea el artículo IndexedDB y sus sub-páginas, que documentan los tipos de objetos utilizados por IndexedDB, así como los métodos de las API síncrona y asíncrona.

- -

Visión general de IndexedDB

- -

IndexedDB le permite almacenar y obtener objetos indizados a partir de una "llave". Todos los cambios realizados a la base de datos ocurren dentro de transacciones. Como la mayoría de las soluciones de almacenamiento web, IndexedDB sigue una política de mismo origen, por lo que aún cuando se puede acceder a datos almacenados en un dominio, no se pueden acceder a datos a través de distintos dominios.

- -

La API incluye una variante asíncrona y una síncrona. La variante asíncrona puede ser utilizada en la mayoría de los casos, incluyendo WebWorkers, mientras la variante síncrona está diseñada para ser utilizada solo con WebWorkers. Actualmente, ninguno de los navegadores principales soportan la API síncrona. Sin embargo, aún cuando la API síncrona sea soportada, en la mayoría de los casos de uso de IndexedDB lo más probable es que se utilice la API asíncrona.

- -

IndexedDB es una alternativa a WebSQL, que fue marcada como obsoleta por W3C el 18 de Noviembre de 2010. Aún cuando IndexedDB y WebSQL son soluciones para el almacenamiento, éstas no ofrecen las mismas funcionalidades. WebSQL es un sistema relacional de acceso a datos, mientras que IndexedDB es un sistema de tablas indizadas.

- -

Conceptos principales

- -

Si usted tiene alguna idea de cómo trabajan otros tipos de bases de datos, podría tener algún conflicto de conceptos al trabajar con IndexedDB. Por esta razón mantenga los siguientes conceptos importantes en mente:

- - - -

Definiciones

- -

Esta sección define y explica los términos utilizados en la API de IndexedDB.

- -

Base de Datos

- -
-
base de datos
-
Un repositorio de información, típicamente compuesto de uno o más  almacenes de objetos. Cada base de datos debe tener: -
    -
  • Nombre. Identifica la base de datos dentro de un mismo origen y no cambia a lo largo de la existencia de ésta. El nombre puede ser cualquier cadena de caracteres (incluyendo una vacía).
  • -
  • -

    Versión actual. Cuando una base de datos se crea por primera vez, la versión es el número entero 1 si no se indica otra cosa. Cada base de datos puede tener una y sólo una versión en cualquier momento.

    -
  • -
-
-
almacén de objetos
-
-

El mecanismo a través del cual los datos son almacenados en la base de datos. El almacén de objetos mantiene registros de manera persistente, que son pares de llave-valor. Los registros dentro de un almacén de objetos son ordenados de acuerdo con las llaves en orden ascendente.

- -

Todo almacén de objetos debe tener un nombre que es único a lo largo de su base de datos. Opcionalmente puede tener un generador de llaves y una ruta de llaves. Si el almacén tiene una ruta de llaves, éste utiliza llaves en línea; si no, utiliza llaves fuera de línea.

- -

Para documentación de referencia sobre los almacenes de objetos, vew IDBObjectStore o IDBObjectStoreSync.

-
-
versión
-
Cuando una base de datos es creada por primera vez, su versión es 1. Cada base de datos tiene una versión en cualquier momento y no puede tener varias versiones al mismo tiempo. La única manera de cambiar la versión es abrir la base de datos con una versión mayor a la actual. Esto arranca una transacción versionchange y dispara el evento upgradeneeded. El único momento cuando se puede actualizar el esquema de la base de datos es dentro del manejador de este evento.
-
Nota: Esta definición describe la especificación más actual, que solo está implementada por las versiones más nuevas de los navegadores. Los navegadores más antiguos implementaron el método IDBDatabase.setVersion(), que ya ha sido marcado obsoleto y removido.
-
conexión a la base de datos
-
Una operación creada al abrir una base de datos. Una base de datos puede tener múltiples conexiónes al mismo tiempo.
-
transacción
-
-

Un conjunto atómico y durable de operaciónes de acceso y modificación de datos sobre una base de datos particular. Esta es la manera cómo se interactúa con los datos de una base de datos. De hecho, cualquier lectura o modificación de datos en la base de datos debe ocurrir dentro de una transacción.

- -

Una conexión a la base de datos puede tener varias transacciones activas, siempre que las operaciones de escrituras no tengan ámbitos que se solapen. El ámbito de las transacciones, que es definido al momento en que éstas son creadas, determina con qué almacenes de datos puede interactuar ésta y permanece constante a lo largo de su existencia. Así, por ejemplo, si una conexión tiene una transacción escribiendo con un ámbito que abarca solo el almacén flyingMonkey, se puede iniciar una segunda que tenga como ámbito los almacenes unicornCentaur y unicornPegasus. En el caso de las transacciones de lectura, se pueden tener varias aún cuando se solapen.

- -

Se espera que las transacciones tengan una existencia corta, de manera que el navegador puede cancelar una transacción que tome demasiado tiempo para liberar recursos que la misma tenga bloqueados. Usted puede abortar la transacción, lo que deshace los cambios hechos a la base de datos durante la misma. Ni siquiera es necesario esperar a que la transacción inicie para abortarla.

- -

Los tres modos de transacción son: readwrite, readonly, y versionchange. La única manera de crear y borrar almacenes es usar una transacción versionchange. Para aprender más sobre los tipos de transacción, vea al artículo de referencia de IndexedDB.

- -

Debido a que todo sucede dentro de una transacción, este es un concepto muy importante. Para aprender más sobre las transacciones, especialmente sobre como se relacionan con el versionado, vea IDBTransaction, que también cuenta con documentación de referencia. Para la documentación sobre la API asíncrona, vea IDBTransactionSync.

-
-
solicitud
-
La operación por medio de la cual se lee o se escribe en una base de datos. Toda solicitud representa una y solo una operación de lectura o escritura.
-
índice
-
-

Un almacén especializado para buscar registros en otro almacén, llamado almacén de objetos referenciado. El índice es un almacenamiento persistente llave-valor donde el valor es una llave del almacén referenciado. Los registros en un índice son rellenados automáticamente cada vez que se modifican los registros del almacén referenciado. Cada registro en un índice puede apuntar solo a un registro de su almacén referenciado, pero varios índices pueden apuntar al mismo almacén.

- -

Alternativamente, se pueden realizar búsquedas en un almacén de objetos usando la llave.

- -

Para aprender más sobre el uso de los índices, vea Usando IndexedDB. Para documentación de referencia, vea IDBKeyRange.

-
-
- -

Llave y valor

- -
-
llave
-
-

Es uno de los atributos del objeto a partir del cual los demás objetos son organizados y obtenidos desde el almacén de objetos. El almacén puede derivar una llave desde uno de tres orígenes: un generador de llaves, una ruta de llave, y un valor indicado de forma explícita. La llave debe ser de un tipo de datos que tenga un número creciente en relación con los objetos almacenados previamente. Cada registro en un almacén de datos debe tener una llave única en el almacén, de manera que no se pueden tener varios objetos con la misma llave en un almacén de objetos dado.

- - -

Una llave puede ser de uno de los siguientes tipos: String, Date, float, y Array. Para los arreglos, la llave puede tener un rango desde un valor vacío hasta infinito, y puede incluirse un arreglo dentro de otro. No se requiere usar solo cadenas o enteros para las llaves.

- -

Como alternativa, se pueden realizar búsquedas de objetos usando un índice.

-
-
generador de llaves
-
Es un mecanismo para producir nuevas llaves en una secuencia ordenada. Si un almacén de objetos no tiene un generador de llaves, entonces la aplicación debe proveer llaves para los registros que se almacenen. Los generadores no son compartidos entre almacenes. Esto es un detalle de implementación de los navegadores, porque en desarrollo web, realmente no se crea o se accede a un generador de llaves.
-
llaves en línea
-
Es una llave que se almacena como parte del valor almacenado. La manera como se determina cuál es la llave es utilizando una  ruta de llave. Una llave en línea puede obtenerse con un generador. Después de que la llave ha sido generada, esta puede almacenarse en el valor usando la ruta del atributo o puede ser usada directamente como llave.
-
llave fuera de línea
-
Una llave que se almacena separada del valor.
-
ruta de llave
-
Define de dónde se debe extraer la llave desde un valor en el almacén o en un índice. Una ruta de llave válida puede incluir alguno de los siguientes: una cadena vacía, un identificador de JavaScript, o múltiples identificadores de JavaScript separados con puntos. No puede incluir espacios.
-
valor
-
-

Cada registro tiene un valor, el cual puede ser cualquier cosa que pueda ser expresada en JavaScript, incluyendo: booleanos, números, cadenas, fechas, objetos, arreglos, expresiones regulares, undefined, y null.

- -

Cuando un objeto o un arreglo es almacenado, las propiedades y valores en ese objeto o arreglo pueden ser cualquier cosa que sea un valor válido.

- -

Se pueden almacenar Blobs y archivos. cf. especificación.

-
-
- -

Rango y ámbito

- -
-
ámbito
-
El conjunto de almacenes de objetos e índices en los que una transacción aplica. Los ámbitos de varias transacciones de solo lectura pueden solaparse y ejecutarse al mismo tiempo. En cambio, los ámbitos de transacciones de escritura no pueden solaparse. Aún así se pueden crear varias transacciones con el mismo ámbito al mismo tiempo, pero éstas serán manejadas por una cola y ejecutadas una detrás de otra.
-
cursor
-
Un mecanismo para iterar a través de múltiples registros con un rango de llaves. El cursor tiene un orígen que indica que índice o almacén de datos está iterando. El cursor tiene una posición dentro del rango, y se mueve en dirección creciente o decreciente en el orden de las llaves de cada registro. Para obtener documentación de referencia sobre cursores, vea IDBCursor o IDBCursorSync.
-
rango de llaves
-
-

Un intervalo continuo sobre algún tipo de datos utilizado para las llaves. Los registros pueden obtenerse desde los almacenes e índices usando llaves o un rango de llaves. Los rangos pueden limitarse o filtrarse con umbrales inferiores y superiores. Por ejemplo, se puede iterar sobre todos los valores de una llave desde x hasta y.

- -

Para documentación de referencia sobre los rangos de llaves, vea IDBKeyRange.

-
-
- -

Limitaciones

- -

IndexedDB está diseñado para cubrir la mayoría de los casos en los que se necesita almacenamiento del lado del cliente. Sin embargo, no están contemplados en su diseño unos pocos casos como los siguientes:

- - - -

Adicionalmente, tenga en cuenta que los navegadores podrían eliminar la base de datos, como en las siguientes condiciones:

- - - -

Las circunstancias exactas y capacidades de los navegadores cambian con el tiempo, pero la filosofía de los navegadores es, en general, hacer lo posible por conservar los datos.

- -
-

Advertencia: Al momento, debido a errores o a propósito, es imposible abrir una base de datos IndexedDB desde un Web App. Esto requiere mayor investigación para documentarlo.

-
- -

Próximo paso

- -

Ok, ahora con estos conceptos generales bajo nuestros cinturones, podemos seguir a cosas más concretas. Para un tutorial sobre como utilizar la API, vea Usando IndexedDB.

- -

Vea también

- -

Especificación

- - - -

Referencia

- - - -

Tutoriales

- - - -

Artículo relacionado

- - diff --git a/files/fr/_redirects.txt b/files/fr/_redirects.txt index 660d57b046..c304f382b3 100644 --- a/files/fr/_redirects.txt +++ b/files/fr/_redirects.txt @@ -2130,9 +2130,9 @@ /fr/docs/Indentation_homogène_des_listes /fr/docs/Web/CSS/CSS_Lists_and_Counters/Consistent_list_indentation /fr/docs/IndexedDB /fr/docs/Web/API/IndexedDB_API /fr/docs/IndexedDB-840092-dup /fr/docs/Web/API/IndexedDB_API -/fr/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /fr/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/fr/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /fr/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /fr/docs/IndexedDB/Browser_storage_limits_and_eviction_criteria /fr/docs/Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria -/fr/docs/IndexedDB/Concepts_basiques_IndexedDB /fr/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/fr/docs/IndexedDB/Concepts_basiques_IndexedDB /fr/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /fr/docs/IndexedDB/Using_IndexedDB /fr/docs/Web/API/IndexedDB_API/Using_IndexedDB /fr/docs/Introduction_à_SVG_dans_HTML /fr/docs/Web/SVG/Tutorial/SVG_In_HTML_Introduction /fr/docs/Introduction_à_XML /fr/docs/Web/XML/XML_introduction @@ -3589,7 +3589,7 @@ /fr/docs/Web/API/API_HTML_Drag_and_Drop /fr/docs/Web/API/HTML_Drag_and_Drop_API /fr/docs/Web/API/API_HTML_Drag_and_Drop/Opérations_de_glissement /fr/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations /fr/docs/Web/API/API_IndexedDB /fr/docs/Web/API/IndexedDB_API -/fr/docs/Web/API/API_IndexedDB/Basic_Concepts_Behind_IndexedDB /fr/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/fr/docs/Web/API/API_IndexedDB/Basic_Concepts_Behind_IndexedDB /fr/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /fr/docs/Web/API/API_IndexedDB/Browser_storage_limits_and_eviction_criteria /fr/docs/Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria /fr/docs/Web/API/API_IndexedDB/Using_IndexedDB /fr/docs/Web/API/IndexedDB_API/Using_IndexedDB /fr/docs/Web/API/API_fichier_systeme /fr/docs/Web/API/File_and_Directory_Entries_API @@ -3789,6 +3789,7 @@ /fr/docs/Web/API/HTMLTableElement.insertRow /fr/docs/Web/API/HTMLTableElement/insertRow /fr/docs/Web/API/IDBEnvironment/indexedDB /fr/docs/Web/API/WindowOrWorkerGlobalScope/indexedDB /fr/docs/Web/API/IDBRequest/blocked_event /fr/docs/Web/API/IDBOpenDBRequest/blocked_event +/fr/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /fr/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /fr/docs/Web/API/Location.assign /fr/docs/Web/API/Location/assign /fr/docs/Web/API/Location.reload /fr/docs/Web/API/Location/reload /fr/docs/Web/API/Location.replace /fr/docs/Web/API/Location/replace @@ -4744,7 +4745,7 @@ /fr/docs/Web/JavaScript/Reference/Erreurs/Stmt_after_return /fr/docs/Web/JavaScript/Reference/Errors/Stmt_after_return /fr/docs/Web/JavaScript/Reference/Erreurs/Strict_Non_Simple_Params /fr/docs/Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params /fr/docs/Web/JavaScript/Reference/Erreurs/Too_much_recursion /fr/docs/Web/JavaScript/Reference/Errors/Too_much_recursion -/fr/docs/Web/JavaScript/Reference/Erreurs/Typed_array_invalid_arguments /fr/docs/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +/fr/docs/Web/JavaScript/Reference/Erreurs/Typed_array_invalid_arguments /fr/docs/orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /fr/docs/Web/JavaScript/Reference/Erreurs/Undeclared_var /fr/docs/Web/JavaScript/Reference/Errors/Undeclared_var /fr/docs/Web/JavaScript/Reference/Erreurs/Undefined_prop /fr/docs/Web/JavaScript/Reference/Errors/Undefined_prop /fr/docs/Web/JavaScript/Reference/Erreurs/Unexpected_token /fr/docs/Web/JavaScript/Reference/Errors/Unexpected_token @@ -4755,6 +4756,7 @@ /fr/docs/Web/JavaScript/Reference/Erreurs/in_operator_no_object /fr/docs/Web/JavaScript/Reference/Errors/in_operator_no_object /fr/docs/Web/JavaScript/Reference/Erreurs/invalid_right_hand_side_instanceof_operand /fr/docs/Web/JavaScript/Reference/Errors/invalid_right_hand_side_instanceof_operand /fr/docs/Web/JavaScript/Reference/Erreurs/is_not_iterable /fr/docs/Web/JavaScript/Reference/Errors/is_not_iterable +/fr/docs/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /fr/docs/orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /fr/docs/Web/JavaScript/Reference/Fonctions /fr/docs/Web/JavaScript/Reference/Functions /fr/docs/Web/JavaScript/Reference/Fonctions/Définition_de_méthode /fr/docs/Web/JavaScript/Reference/Functions/Method_definitions /fr/docs/Web/JavaScript/Reference/Fonctions/Fonctions_fléchées /fr/docs/Web/JavaScript/Reference/Functions/Arrow_functions diff --git a/files/fr/_wikihistory.json b/files/fr/_wikihistory.json index 3316143f7c..aa4972b8c4 100644 --- a/files/fr/_wikihistory.json +++ b/files/fr/_wikihistory.json @@ -18245,17 +18245,6 @@ "moins52" ] }, - "Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { - "modified": "2020-03-19T07:25:26.127Z", - "contributors": [ - "ChristopheBoucaut", - "loella16", - "Alpha", - "SphinxKnight", - "teoli", - "julienw" - ] - }, "Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria": { "modified": "2019-07-09T03:14:33.430Z", "contributors": [ @@ -35289,12 +35278,6 @@ "jcletousey" ] }, - "Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { - "modified": "2020-03-12T19:45:50.257Z", - "contributors": [ - "SphinxKnight" - ] - }, "Web/JavaScript/Reference/Errors/Undeclared_var": { "modified": "2020-03-12T19:43:41.533Z", "contributors": [ @@ -45016,6 +44999,17 @@ "loella16" ] }, + "orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { + "modified": "2020-03-19T07:25:26.127Z", + "contributors": [ + "ChristopheBoucaut", + "loella16", + "Alpha", + "SphinxKnight", + "teoli", + "julienw" + ] + }, "orphaned/Web/API/Notation": { "modified": "2019-03-18T21:40:13.820Z", "contributors": [ @@ -45234,6 +45228,12 @@ "Goofy" ] }, + "orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { + "modified": "2020-03-12T19:45:50.257Z", + "contributors": [ + "SphinxKnight" + ] + }, "orphaned/Web/JavaScript/Reference/Global_Objects/WeakSet/clear": { "modified": "2020-10-15T21:30:59.712Z", "contributors": [ diff --git a/files/fr/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/fr/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..70ba6ab52c --- /dev/null +++ b/files/fr/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,210 @@ +--- +title: Les concepts basiques d'IndexedDB +slug: orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +tags: + - Avancé + - IndexedDB + - concepts +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +original_slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +

IndexedDB est un moyen pour permettre le stockage de données dans le navigateur d'un utilisateur, de manière persistante. Ses fonctions de recherche avancées permettent de créer des applications qui fonctionnent tant connectées que déconnectées. IndexedDB est utile pour créer des applications qui stockent une grande quantité de données (par exemple : un catalogue de DVDs dans une bibliothèque) et des applications qui n'ont pas forcément besoin d'une connectivité Internet continue (par exemple : des clients de messagerie électronique, des listes de tâches, des bloc-notes).

+ +

À propos de ce document

+ +

Ce document introduit les concepts et les termes essentiels d'IndexedDB. Vous aurez une vue d'ensemble et vous comprendrez les concepts-clés.

+ +

Vous pourrez trouver ici :

+ + + +

Vue d'ensemble d'IndexedDB

+ +

IndexedDB vous permet de stocker et récupérer des objets qui sont indexés avec une "clé". Tous les changements que vous faites dans la base de données sont forcément transactionnels. Comme la plupart des solutions de stockage du web, IndexedDB respecte la politique de sécurité utilisant l'origne (same-origin policy). Ainsi, vous pouvez accéder aux données stockées d'un domaine, alors que vous ne pouvez pas accéder aux données de domaines différents.

+ +

IndexedDB est une API asynchrone qui peut être utilisée dans la plupart des contextes, Web Workers inclus. Elle comportait également une version synchrone prévue pour être utilisée dans des Web Workers. mais cette option a été retirée de la spécification en raison du manque d'intérêt de la communauté Web.

+ +

IndexedDB est une alternative à l'API WebSQL Database, qui a été dépréciée par le W3C le 18 novembre 2010. Alors que ces APIs sont toutes deux des solutions de stockage, elles n'offrent pas les mêmes fonctionnalités. WebSQL Database est un système d'accès à une base de données relationnelle alors qu'IndexedDB est un système de table indexée. 

+ +

Les grands concepts

+ +

Si vous avez l'habitude de travailler avec d'autres types de bases de données, vous pourrez être désorienté par l'utlisation d'IndexedDB. Mais il suffit de garder les concepts importants suivants en tête :

+ + + +

Définitions

+ +

Cette section définit et explique les termes utilisés dans l'API IndexedDB.

+ +

Database (base de données)

+ +
+
database (base de données)
+
Un référentiel d'informations, comprenant généralement un ou plusieurs objets de stockage. Chaque base de données doit avoir les éléments suivants : +
    +
  • Name . (nom) Il identifie la base de données dans une origine spécifique et reste constant tout au long de la durée de sa vie. Le nom peut être n'importe quelle valeur de chaîne de caractères (y compris une chaîne vide).
  • +
  • Current version (version actuelle). Lors de la création de la base de données, sa version est le nombre entier 1. Chaque base de données ne peut avoir qu'une seule version à un moment donné .
  • +
+
+
durable
+
Dans Firefox, IndexedDB était durable, ce qui signifie que dans une transaction readwrite (lecture/écriture) {{domxref ("IDBTransaction.on complet")}} était déclenché uniquement lorsque toutes les données étaient garanties, avant d'être écrites sur le disque.
+
À partir de Firefox 40, les transactions IndexedDB ont des garanties de durabilité relachées pour augmenter les performances (voir {{Bug ("1112702")}}) ; comportement identique à celui des autres navigateurs qui mettent en oeuvre IndexedDB. Dans ce cas, l'événement {{Event ("complete")}} est déclenché après la réception par le système d'exploitation de la commande d'écriture, mais potentiellement avant l'écriture effective de ces données sur le disque. L'événement peut donc être livré plus rapidement qu'avant, mais il existe un petit risque que la transaction entière soit perdue si le système d'exploitation l'écrase ou s'il y a une perte de puissance du système avant l'écriture sur le disque. Étant donné que ces événements catastrophiques sont rares, la plupart des consommateurs ne devraient pas nécessairement s'en préoccuper davantage.
+
+ +
+

Note : Dans Firefox, si vous souhaitez être sûr de la durabilité pour une raison ou une autre (par exemple, vous stockez des données critiques qui ne peuvent pas être recalculées plus tard), vous pouvez forcer une transaction d'écriture sur le disque avant la délivrance de l'évènement complete  par la création d'une transaction utilisant le mode expérimental (non standard) readwriteflush  (voir {{domxref("IDBDatabase.transaction")}}).  Ceci est actuellement expérimental et ne peut être utilisé que si la préférence dom.indexedDB.experimental est renseignée avec " true " (vrai) dans about:config.

+
+ +
+
+
object store (objet de stockage)
+
+

Le mécanisme avec lequel les données sont stockées dans la base de données. L'objet de stockage maintient constamment ses enregistrements, lesquels sont des paires  "key-value" (clé-valeur). Les enregistrements dans l'objet de stockage sont triés dans l'ordre ascendant des "keys" (clés).

+ +

Chaque objet de stockage doit avoir un nom qui est unique dans la base de données. Il peut éventuellement avoir un key generator (générateur de clé) et un key path (chemin de clé). S'il a un "key path", il utilise in-line keys (clés en ligne) ; sinon, il utilise out-of-line keys (clé hors ligne).

+ +

Pour la documentation de référence sur les objets de stockage, voir IDBObjectStore ou IDBObjectStoreSync.

+
+
version
+
À la première création de la base de données, sa version est le nombre entier 1. Chaque base de données possède une seule version à un moment donné ; il ne peut pas exister plusieurs versions dans le même temps. La seule façon de changer la version est de l'ouvrir avec une version plus haute. Ceci démarre une transaction VERSION_CHANGE et lance un évènement upgradeneeded. Le seul endroit où le schéma de la base de données peut être mis à jour est à l'intérieur du gestionnaire de cet événement.
+
Note : Cette définition décrit les spécifications les plus récentes, qui ne sont implémentées que dans des navigateurs à jour. Les anciens navigateurs ont implémenté la méthode IDBDatabase.setVersion() maintenant obsolète et supprimée.
+
database connection (connexion de la base de données)
+
Une opération créée en ouvrant une database (base de données). Une base de données peut avoir plusieurs connexions en même temps.
+
transaction
+
+

Un ensemble atomique d'accès aux données et d'opérations de modification des données sur une base de données particulière. C'est la façon dont vous interagissez avec les données dans une base. En fait, toute lecture ou changement dans la base de données doit se produire dans une transaction.

+ +

Une connexion à la base de données peut avoir plusieurs transactions actives associées à la fois, pourvu que les transactions d'écriture n'aient pas de chevauchement scopes. La portée (scope) des transactions, qui est définie lors de la création, détermine l'objet avec lequel la transaction peut interagir, et reste constante pour la durée de vie de la transaction. Ainsi, par exemple, si une connexion à la base de données a déjà une transaction d'écriture avec une portée qui couvre simplement l'objet de stockage flyingMonkey , vous pouvez commencer une seconde transaction avec une portée sur les objets de stockage unicornCentaur et unicornPegasus. En ce qui concerne les transactions de lecture, vous pouvez en avoir plusieurs - même avec chevauchements.

+ +

Les transactions doivent être de courte durée, pour que le navigateur puisse mettre fin à une transaction trop longue, afin de libérer des ressources de stockage verrouillées par cette dernière. Vous pouvez annuler la transaction, ce qui modifie les changements apportés à la base de données dans la transaction. Et vous n'avez même pas à attendre que la transaction commence ou soit active pour l'annuler.

+ +

Les trois modes de transaction sont : " readwrite " (lecture/écriture), " readonly " (lecture seule), et " versionchange " (changement de version). La seule manière de créer et supprimer les objets de stockage et les index est d'utiliser une transaction versionchange . Pour en apprendre plus sur les types de transactions, voir l'article de référence pour IndexedDB.

+ +

Parce que tout se passe au sein d'une transaction, c'est un concept très important dans IndexedDB. Pour en savoir plus sur les transactions, en particulier sur la façon dont elles se rapportent aux versions, voir IDBTransaction, qui a également une documentation de référence . Pour la documentation sur l'API synchrone, voir IDBTransactionSync.

+
+
request (requêtes)
+
L'opération par laquelle la lecture et l'écriture sur une base de données est effectuée. Chaque requête représente une opération de lecture ou d'écriture.
+
index
+
+

Un index est un objet de stockage spécialisé pour rechercher des enregistrements dans un autre objet de stockage appelé " referenced object store"  (objet de stockage référencé). L'index est un stockage persistant de key-value (clé-valeur)  dans lequel la partie "value" des enregistrements contient la partie "key" d'un enregistrement de l'objet de stockage référencé. Les enregistrements dans un index sont automatiquement remplis chaque fois que ceux de l'objet référencé sont insérés, mis à jour ou supprimés. Chaque enregistrement d'un index ne peut indiquer qu'un seul enregistrement dans son objet référencé, mais plusieurs index peuvent référencer le même objet. Lorsque l'objet référencé change, tous les index qui s'y réfèrent sont mis à jour automatiquement.

+ +

Vous pouvez également rechercher des enregistrements dans un objet de stockage en utilisant la clé.

+ +

Pour en apprendre plus sur l'utilisation des index, voir Using IndexedDB. Pour la documentation de référence sur l'index, voir IDBKeyRange.

+
+
+ +

Key and value (clé et valeur)

+ +
+
key (clé)
+
+

Une valeur de données par laquelle les valeurs stockées sont organisées et récupérées dans l'objet de stockage . Celui-ci peut obtenir la clé de l'une des trois sources : un générateur de clés, un chemin de clé et une valeur explicitement spécifiée. La clé doit être d'un type de données qui a un nombre supérieur au précédent. Chaque enregistrement doit avoir une clé unique dans l'objet de stockage, de sorte que celui-ci ne peut comporter plusieurs enregistrements avec la même clé.

+ +

Une clé peut être de l'un des types suivants : string (chaîne de caractères), date, float (flottante), binary blob (blob binaire) et array (tableau). Pour les tableaux, la valeur de la clé peut être comprise entre vide et l'infini. Et vous pouvez inclure un tableau dans un tableau.

+ +

Vous pouvez également rechercher des enregistrements dans un objet de stockage en utilisant l'index.

+
+
key generator (générateur de clé)
+
Un mécanisme pour produire de nouvelles clés dans une séquence ordonnée. Si un objet de stockage n'a pas de générateur de clé, l'application doit fournir les clés des enregistrements stockés. Les générateurs ne sont pas partagés entre les objets de stockage. Il s'agit d'un détail concernant les navigateurs, car dans le développement web, vous ne créez pas réellement ou ne gérez pas les accès aux générateurs de clés.
+
in-line key (clé en ligne)
+
Une clé qui est stockée comme partie d'une valeur de stockage. Elle est trouvée en utilisant "key path" (chemin de clé). Une clé en ligne peut être créée par un générateur. Une fois la clé générée, elle peut être stockée dans la valeur utilisant le "key path" ou être utilisée comme clé.
+
out-of-line key (clé hors ligne)
+
Une clé stockée séparément de la valeur stockée.
+
key path (chemin de clé)
+
Définit où le navigateur doit extraire la clé d'une valeur dans l'objet de stockage ou l'index. Un chemin de clé valide peut inclure l'un des éléments suivants : une chaîne vide, un identifiant JavaScript ou plusieurs identifiants JavaScript séparés par des périodes, ou un tableau contenant ces éléments. Il ne peut pas inclure d'espaces.
+
value (valeur)
+
+

Chaque enregistrement a une valeur, qui peut inclure tout ce qui peut être exprimé en JavaScript, y compris : boolean (bouléen), number (nombre), string (chaîne de caractères), date, object (objet), array (tableau), regexp, undefined (indéfini), and null (nul).

+ +

Quand un objet ou un tableau est stocké, les propriétés et valeurs dans cet objet ou ce tableau peuvent aussi être toute valeur valide.

+ +

Blobs et fichiers peuvent être stockés, voir specification.

+
+
+ +

Intervalle et portée

+ +
+
scope (portée ou étendue)
+
L'ensemble des objets de stockage et index auxquels s'applique une transaction. Les portées des transactions en lecture seule peuvent se chevaucher et s'exécuter en même temps. Par contre, les portées des transactions d'écriture ne peuvent pas se chevaucher. Vous pouvez toujours démarrer plusieurs transactions avec la même portée en même temps, mais elles entrent dans une file d'attente et s'exécutent l'une après l'autre.
+
cursor (curseur)
+
Un mécanisme pour l'itération de plusieurs enregistrements avec une "key range" (intervalle de clés). Le curseur possède une source qui indique quel index ou objet stocké est itéré. Il a une position dans l'intervalle et se déplace dans une direction qui augmente ou diminue dans l'ordre des clés d'enregistrement. Pour la documentation de référence sur les curseurs, voir IDBCursor ou IDBCursorSync.
+
key range (intervalle de clés)
+
+

Un intervalle continu sur un type de données utilisé pour les clés. Les enregistrements peuvent être récupérés à partir des objets de stockage et des index à l'aide de touches ou d'un intervalle de clés. Vous pouvez limiter ou filtrer l'intervalle en utilisant les limites inférieures et supérieures. Par exemple, vous pouvez itérer sur toutes les valeurs d'une clé entre x et y.

+ +

Pour la documentation de référence sur "key range", voir IDBKeyRange.

+
+
+ +

Limitations

+ +

IndexedDB est conçu pour couvrir la plupart des cas qui nécessitent un stockage côté client. Cependant, il n'est pas adapté pour quelques cas comme les suivants :

+ + + +

En outre, sachez que les navigateurs peuvent effacer la base de données, comme dans les conditions suivantes :

+ + + +

Les circonstances exactes et les capacités du navigateur changent au fil du temps, mais la philosophie générale des fournisseurs de navigateurs est de faire les efforts nécessaires pour conserver les données lorsque c'est possible.

+ +

Étape suivante

+ +

Avec ces grands concepts dans nos poches, nous pouvons obtenir des choses plus concrètes. Pour un tutoriel sur l'utilisation de l'API, voir Using IndexedDB.

+ +

Voir aussi

+ +

Spécification

+ + + +

Référence

+ + + +

Tutoriels

+ + + +

Article connexe

+ + diff --git a/files/fr/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/fr/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html new file mode 100644 index 0000000000..0aa9b42d9c --- /dev/null +++ b/files/fr/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html @@ -0,0 +1,77 @@ +--- +title: 'TypeError: invalid arguments' +slug: orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +tags: + - Erreurs + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +original_slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
TypeError: invalid arguments (Firefox)
+ +

Type d'erreur

+ +

{{jsxref("TypeError")}}

+ +

Quel est le problème ?

+ +

Les constructeurs de tableaux typés ont besoin :

+ + + +

afin de créer un nouveau tableau typé. Si on utilise un autre argument, on ne pourra pas créer de tableau typé valide.

+ +

Exemples

+ +

Il est par exemple impossible de construire un tableau typé {{jsxref("Uint8Array")}} à partir d'une chaîne de caractères :

+ +
var ta = new Uint8Array("nope");
+// TypeError: invalid arguments
+
+ +

Voici différentes façons de créer un tableau typué {{jsxref("Uint8Array")}} :

+ +
// À partir d'une longueur
+var uint8 = new Uint8Array(2);
+uint8[0] = 42;
+console.log(uint8[0]); // 42
+console.log(uint8.length); // 2
+console.log(uint8.BYTES_PER_ELEMENT); // 1
+
+// À partir d'un tableau
+var arr = new Uint8Array([21,31]);
+console.log(arr[1]); // 31
+
+// À partir d'un autre tableau typé
+var x = new Uint8Array([21, 31]);
+var y = new Uint8Array(x);
+console.log(y[0]); // 21
+
+// À partir d'un ArrayBuffer
+var buffer = new ArrayBuffer(8);
+var z = new Uint8Array(buffer, 1, 4);
+
+// À partir d'un itérable
+var iterable = function*(){ yield* [1,2,3]; }();
+var uint8 = new Uint8Array(iterable);
+// Uint8Array[1, 2, 3]
+
+ +

Voir aussi

+ + diff --git a/files/fr/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/fr/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html deleted file mode 100644 index b8cb7d6cd8..0000000000 --- a/files/fr/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Les concepts basiques d'IndexedDB -slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -tags: - - Avancé - - IndexedDB - - concepts -translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -original_slug: Web/API/API_IndexedDB/Basic_Concepts_Behind_IndexedDB ---- -

{{DefaultAPISidebar("IndexedDB")}}

- -

IndexedDB est un moyen pour permettre le stockage de données dans le navigateur d'un utilisateur, de manière persistante. Ses fonctions de recherche avancées permettent de créer des applications qui fonctionnent tant connectées que déconnectées. IndexedDB est utile pour créer des applications qui stockent une grande quantité de données (par exemple : un catalogue de DVDs dans une bibliothèque) et des applications qui n'ont pas forcément besoin d'une connectivité Internet continue (par exemple : des clients de messagerie électronique, des listes de tâches, des bloc-notes).

- -

À propos de ce document

- -

Ce document introduit les concepts et les termes essentiels d'IndexedDB. Vous aurez une vue d'ensemble et vous comprendrez les concepts-clés.

- -

Vous pourrez trouver ici :

- - - -

Vue d'ensemble d'IndexedDB

- -

IndexedDB vous permet de stocker et récupérer des objets qui sont indexés avec une "clé". Tous les changements que vous faites dans la base de données sont forcément transactionnels. Comme la plupart des solutions de stockage du web, IndexedDB respecte la politique de sécurité utilisant l'origne (same-origin policy). Ainsi, vous pouvez accéder aux données stockées d'un domaine, alors que vous ne pouvez pas accéder aux données de domaines différents.

- -

IndexedDB est une API asynchrone qui peut être utilisée dans la plupart des contextes, Web Workers inclus. Elle comportait également une version synchrone prévue pour être utilisée dans des Web Workers. mais cette option a été retirée de la spécification en raison du manque d'intérêt de la communauté Web.

- -

IndexedDB est une alternative à l'API WebSQL Database, qui a été dépréciée par le W3C le 18 novembre 2010. Alors que ces APIs sont toutes deux des solutions de stockage, elles n'offrent pas les mêmes fonctionnalités. WebSQL Database est un système d'accès à une base de données relationnelle alors qu'IndexedDB est un système de table indexée. 

- -

Les grands concepts

- -

Si vous avez l'habitude de travailler avec d'autres types de bases de données, vous pourrez être désorienté par l'utlisation d'IndexedDB. Mais il suffit de garder les concepts importants suivants en tête :

- - - -

Définitions

- -

Cette section définit et explique les termes utilisés dans l'API IndexedDB.

- -

Database (base de données)

- -
-
database (base de données)
-
Un référentiel d'informations, comprenant généralement un ou plusieurs objets de stockage. Chaque base de données doit avoir les éléments suivants : -
    -
  • Name . (nom) Il identifie la base de données dans une origine spécifique et reste constant tout au long de la durée de sa vie. Le nom peut être n'importe quelle valeur de chaîne de caractères (y compris une chaîne vide).
  • -
  • Current version (version actuelle). Lors de la création de la base de données, sa version est le nombre entier 1. Chaque base de données ne peut avoir qu'une seule version à un moment donné .
  • -
-
-
durable
-
Dans Firefox, IndexedDB était durable, ce qui signifie que dans une transaction readwrite (lecture/écriture) {{domxref ("IDBTransaction.on complet")}} était déclenché uniquement lorsque toutes les données étaient garanties, avant d'être écrites sur le disque.
-
À partir de Firefox 40, les transactions IndexedDB ont des garanties de durabilité relachées pour augmenter les performances (voir {{Bug ("1112702")}}) ; comportement identique à celui des autres navigateurs qui mettent en oeuvre IndexedDB. Dans ce cas, l'événement {{Event ("complete")}} est déclenché après la réception par le système d'exploitation de la commande d'écriture, mais potentiellement avant l'écriture effective de ces données sur le disque. L'événement peut donc être livré plus rapidement qu'avant, mais il existe un petit risque que la transaction entière soit perdue si le système d'exploitation l'écrase ou s'il y a une perte de puissance du système avant l'écriture sur le disque. Étant donné que ces événements catastrophiques sont rares, la plupart des consommateurs ne devraient pas nécessairement s'en préoccuper davantage.
-
- -
-

Note : Dans Firefox, si vous souhaitez être sûr de la durabilité pour une raison ou une autre (par exemple, vous stockez des données critiques qui ne peuvent pas être recalculées plus tard), vous pouvez forcer une transaction d'écriture sur le disque avant la délivrance de l'évènement complete  par la création d'une transaction utilisant le mode expérimental (non standard) readwriteflush  (voir {{domxref("IDBDatabase.transaction")}}).  Ceci est actuellement expérimental et ne peut être utilisé que si la préférence dom.indexedDB.experimental est renseignée avec " true " (vrai) dans about:config.

-
- -
-
-
object store (objet de stockage)
-
-

Le mécanisme avec lequel les données sont stockées dans la base de données. L'objet de stockage maintient constamment ses enregistrements, lesquels sont des paires  "key-value" (clé-valeur). Les enregistrements dans l'objet de stockage sont triés dans l'ordre ascendant des "keys" (clés).

- -

Chaque objet de stockage doit avoir un nom qui est unique dans la base de données. Il peut éventuellement avoir un key generator (générateur de clé) et un key path (chemin de clé). S'il a un "key path", il utilise in-line keys (clés en ligne) ; sinon, il utilise out-of-line keys (clé hors ligne).

- -

Pour la documentation de référence sur les objets de stockage, voir IDBObjectStore ou IDBObjectStoreSync.

-
-
version
-
À la première création de la base de données, sa version est le nombre entier 1. Chaque base de données possède une seule version à un moment donné ; il ne peut pas exister plusieurs versions dans le même temps. La seule façon de changer la version est de l'ouvrir avec une version plus haute. Ceci démarre une transaction VERSION_CHANGE et lance un évènement upgradeneeded. Le seul endroit où le schéma de la base de données peut être mis à jour est à l'intérieur du gestionnaire de cet événement.
-
Note : Cette définition décrit les spécifications les plus récentes, qui ne sont implémentées que dans des navigateurs à jour. Les anciens navigateurs ont implémenté la méthode IDBDatabase.setVersion() maintenant obsolète et supprimée.
-
database connection (connexion de la base de données)
-
Une opération créée en ouvrant une database (base de données). Une base de données peut avoir plusieurs connexions en même temps.
-
transaction
-
-

Un ensemble atomique d'accès aux données et d'opérations de modification des données sur une base de données particulière. C'est la façon dont vous interagissez avec les données dans une base. En fait, toute lecture ou changement dans la base de données doit se produire dans une transaction.

- -

Une connexion à la base de données peut avoir plusieurs transactions actives associées à la fois, pourvu que les transactions d'écriture n'aient pas de chevauchement scopes. La portée (scope) des transactions, qui est définie lors de la création, détermine l'objet avec lequel la transaction peut interagir, et reste constante pour la durée de vie de la transaction. Ainsi, par exemple, si une connexion à la base de données a déjà une transaction d'écriture avec une portée qui couvre simplement l'objet de stockage flyingMonkey , vous pouvez commencer une seconde transaction avec une portée sur les objets de stockage unicornCentaur et unicornPegasus. En ce qui concerne les transactions de lecture, vous pouvez en avoir plusieurs - même avec chevauchements.

- -

Les transactions doivent être de courte durée, pour que le navigateur puisse mettre fin à une transaction trop longue, afin de libérer des ressources de stockage verrouillées par cette dernière. Vous pouvez annuler la transaction, ce qui modifie les changements apportés à la base de données dans la transaction. Et vous n'avez même pas à attendre que la transaction commence ou soit active pour l'annuler.

- -

Les trois modes de transaction sont : " readwrite " (lecture/écriture), " readonly " (lecture seule), et " versionchange " (changement de version). La seule manière de créer et supprimer les objets de stockage et les index est d'utiliser une transaction versionchange . Pour en apprendre plus sur les types de transactions, voir l'article de référence pour IndexedDB.

- -

Parce que tout se passe au sein d'une transaction, c'est un concept très important dans IndexedDB. Pour en savoir plus sur les transactions, en particulier sur la façon dont elles se rapportent aux versions, voir IDBTransaction, qui a également une documentation de référence . Pour la documentation sur l'API synchrone, voir IDBTransactionSync.

-
-
request (requêtes)
-
L'opération par laquelle la lecture et l'écriture sur une base de données est effectuée. Chaque requête représente une opération de lecture ou d'écriture.
-
index
-
-

Un index est un objet de stockage spécialisé pour rechercher des enregistrements dans un autre objet de stockage appelé " referenced object store"  (objet de stockage référencé). L'index est un stockage persistant de key-value (clé-valeur)  dans lequel la partie "value" des enregistrements contient la partie "key" d'un enregistrement de l'objet de stockage référencé. Les enregistrements dans un index sont automatiquement remplis chaque fois que ceux de l'objet référencé sont insérés, mis à jour ou supprimés. Chaque enregistrement d'un index ne peut indiquer qu'un seul enregistrement dans son objet référencé, mais plusieurs index peuvent référencer le même objet. Lorsque l'objet référencé change, tous les index qui s'y réfèrent sont mis à jour automatiquement.

- -

Vous pouvez également rechercher des enregistrements dans un objet de stockage en utilisant la clé.

- -

Pour en apprendre plus sur l'utilisation des index, voir Using IndexedDB. Pour la documentation de référence sur l'index, voir IDBKeyRange.

-
-
- -

Key and value (clé et valeur)

- -
-
key (clé)
-
-

Une valeur de données par laquelle les valeurs stockées sont organisées et récupérées dans l'objet de stockage . Celui-ci peut obtenir la clé de l'une des trois sources : un générateur de clés, un chemin de clé et une valeur explicitement spécifiée. La clé doit être d'un type de données qui a un nombre supérieur au précédent. Chaque enregistrement doit avoir une clé unique dans l'objet de stockage, de sorte que celui-ci ne peut comporter plusieurs enregistrements avec la même clé.

- -

Une clé peut être de l'un des types suivants : string (chaîne de caractères), date, float (flottante), binary blob (blob binaire) et array (tableau). Pour les tableaux, la valeur de la clé peut être comprise entre vide et l'infini. Et vous pouvez inclure un tableau dans un tableau.

- -

Vous pouvez également rechercher des enregistrements dans un objet de stockage en utilisant l'index.

-
-
key generator (générateur de clé)
-
Un mécanisme pour produire de nouvelles clés dans une séquence ordonnée. Si un objet de stockage n'a pas de générateur de clé, l'application doit fournir les clés des enregistrements stockés. Les générateurs ne sont pas partagés entre les objets de stockage. Il s'agit d'un détail concernant les navigateurs, car dans le développement web, vous ne créez pas réellement ou ne gérez pas les accès aux générateurs de clés.
-
in-line key (clé en ligne)
-
Une clé qui est stockée comme partie d'une valeur de stockage. Elle est trouvée en utilisant "key path" (chemin de clé). Une clé en ligne peut être créée par un générateur. Une fois la clé générée, elle peut être stockée dans la valeur utilisant le "key path" ou être utilisée comme clé.
-
out-of-line key (clé hors ligne)
-
Une clé stockée séparément de la valeur stockée.
-
key path (chemin de clé)
-
Définit où le navigateur doit extraire la clé d'une valeur dans l'objet de stockage ou l'index. Un chemin de clé valide peut inclure l'un des éléments suivants : une chaîne vide, un identifiant JavaScript ou plusieurs identifiants JavaScript séparés par des périodes, ou un tableau contenant ces éléments. Il ne peut pas inclure d'espaces.
-
value (valeur)
-
-

Chaque enregistrement a une valeur, qui peut inclure tout ce qui peut être exprimé en JavaScript, y compris : boolean (bouléen), number (nombre), string (chaîne de caractères), date, object (objet), array (tableau), regexp, undefined (indéfini), and null (nul).

- -

Quand un objet ou un tableau est stocké, les propriétés et valeurs dans cet objet ou ce tableau peuvent aussi être toute valeur valide.

- -

Blobs et fichiers peuvent être stockés, voir specification.

-
-
- -

Intervalle et portée

- -
-
scope (portée ou étendue)
-
L'ensemble des objets de stockage et index auxquels s'applique une transaction. Les portées des transactions en lecture seule peuvent se chevaucher et s'exécuter en même temps. Par contre, les portées des transactions d'écriture ne peuvent pas se chevaucher. Vous pouvez toujours démarrer plusieurs transactions avec la même portée en même temps, mais elles entrent dans une file d'attente et s'exécutent l'une après l'autre.
-
cursor (curseur)
-
Un mécanisme pour l'itération de plusieurs enregistrements avec une "key range" (intervalle de clés). Le curseur possède une source qui indique quel index ou objet stocké est itéré. Il a une position dans l'intervalle et se déplace dans une direction qui augmente ou diminue dans l'ordre des clés d'enregistrement. Pour la documentation de référence sur les curseurs, voir IDBCursor ou IDBCursorSync.
-
key range (intervalle de clés)
-
-

Un intervalle continu sur un type de données utilisé pour les clés. Les enregistrements peuvent être récupérés à partir des objets de stockage et des index à l'aide de touches ou d'un intervalle de clés. Vous pouvez limiter ou filtrer l'intervalle en utilisant les limites inférieures et supérieures. Par exemple, vous pouvez itérer sur toutes les valeurs d'une clé entre x et y.

- -

Pour la documentation de référence sur "key range", voir IDBKeyRange.

-
-
- -

Limitations

- -

IndexedDB est conçu pour couvrir la plupart des cas qui nécessitent un stockage côté client. Cependant, il n'est pas adapté pour quelques cas comme les suivants :

- - - -

En outre, sachez que les navigateurs peuvent effacer la base de données, comme dans les conditions suivantes :

- - - -

Les circonstances exactes et les capacités du navigateur changent au fil du temps, mais la philosophie générale des fournisseurs de navigateurs est de faire les efforts nécessaires pour conserver les données lorsque c'est possible.

- -

Étape suivante

- -

Avec ces grands concepts dans nos poches, nous pouvons obtenir des choses plus concrètes. Pour un tutoriel sur l'utilisation de l'API, voir Using IndexedDB.

- -

Voir aussi

- -

Spécification

- - - -

Référence

- - - -

Tutoriels

- - - -

Article connexe

- - diff --git a/files/fr/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/fr/web/javascript/reference/errors/typed_array_invalid_arguments/index.html deleted file mode 100644 index e3f0711d81..0000000000 --- a/files/fr/web/javascript/reference/errors/typed_array_invalid_arguments/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: 'TypeError: invalid arguments' -slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments -tags: - - Erreurs - - JavaScript - - TypeError -translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments -original_slug: Web/JavaScript/Reference/Erreurs/Typed_array_invalid_arguments ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
TypeError: invalid arguments (Firefox)
- -

Type d'erreur

- -

{{jsxref("TypeError")}}

- -

Quel est le problème ?

- -

Les constructeurs de tableaux typés ont besoin :

- - - -

afin de créer un nouveau tableau typé. Si on utilise un autre argument, on ne pourra pas créer de tableau typé valide.

- -

Exemples

- -

Il est par exemple impossible de construire un tableau typé {{jsxref("Uint8Array")}} à partir d'une chaîne de caractères :

- -
var ta = new Uint8Array("nope");
-// TypeError: invalid arguments
-
- -

Voici différentes façons de créer un tableau typué {{jsxref("Uint8Array")}} :

- -
// À partir d'une longueur
-var uint8 = new Uint8Array(2);
-uint8[0] = 42;
-console.log(uint8[0]); // 42
-console.log(uint8.length); // 2
-console.log(uint8.BYTES_PER_ELEMENT); // 1
-
-// À partir d'un tableau
-var arr = new Uint8Array([21,31]);
-console.log(arr[1]); // 31
-
-// À partir d'un autre tableau typé
-var x = new Uint8Array([21, 31]);
-var y = new Uint8Array(x);
-console.log(y[0]); // 21
-
-// À partir d'un ArrayBuffer
-var buffer = new ArrayBuffer(8);
-var z = new Uint8Array(buffer, 1, 4);
-
-// À partir d'un itérable
-var iterable = function*(){ yield* [1,2,3]; }();
-var uint8 = new Uint8Array(iterable);
-// Uint8Array[1, 2, 3]
-
- -

Voir aussi

- - diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index 56a4a572c6..88ecf88204 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -3871,6 +3871,7 @@ /ja/docs/Web/API/IDBFactory.cmp /ja/docs/Web/API/IDBFactory/cmp /ja/docs/Web/API/IDBFactory.deleteDatabase /ja/docs/Web/API/IDBFactory/deleteDatabase /ja/docs/Web/API/IDBFactory.open /ja/docs/Web/API/IDBFactory/open +/ja/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /ja/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /ja/docs/Web/API/LinkStyle /ja/docs/orphaned/Web/API/LinkStyle /ja/docs/Web/API/MediaRecorder_API /ja/docs/conflicting/Web/API/MediaStream_Recording_API /ja/docs/Web/API/MozSocial.closePanel /ja/docs/Web/API/MozSocial/closePanel @@ -4832,6 +4833,7 @@ /ja/docs/Web/JavaScript/Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/Web/JavaScript/Other_JavaScript_tools /ja/docs/Tools /ja/docs/Web/JavaScript/Reference/About/Formatting_Conventions /ja/docs/MDN/Guidelines/Writing_style_guide +/ja/docs/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /ja/docs/orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /ja/docs/Web/JavaScript/Reference/Functions_and_function_scope /ja/docs/Web/JavaScript/Reference/Functions /ja/docs/Web/JavaScript/Reference/Functions_and_function_scope/Arrow_functions /ja/docs/Web/JavaScript/Reference/Functions/Arrow_functions /ja/docs/Web/JavaScript/Reference/Functions_and_function_scope/Default_parameters /ja/docs/Web/JavaScript/Reference/Functions/Default_parameters diff --git a/files/ja/_wikihistory.json b/files/ja/_wikihistory.json index 8d014b55fa..84a2a0691a 100644 --- a/files/ja/_wikihistory.json +++ b/files/ja/_wikihistory.json @@ -17894,17 +17894,6 @@ "Potappo" ] }, - "Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { - "modified": "2020-03-25T11:26:36.526Z", - "contributors": [ - "Uemmra3", - "Wind1808", - "wbamberg", - "SphinxKnight", - "mandel59", - "yyss" - ] - }, "Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria": { "modified": "2019-05-23T13:25:35.305Z", "contributors": [ @@ -38739,12 +38728,6 @@ "YuichiNukiyama" ] }, - "Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { - "modified": "2020-03-12T19:46:14.001Z", - "contributors": [ - "YuichiNukiyama" - ] - }, "Web/JavaScript/Reference/Errors/Undeclared_var": { "modified": "2020-03-12T19:44:07.574Z", "contributors": [ @@ -52285,6 +52268,17 @@ "Wind1808" ] }, + "orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { + "modified": "2020-03-25T11:26:36.526Z", + "contributors": [ + "Uemmra3", + "Wind1808", + "wbamberg", + "SphinxKnight", + "mandel59", + "yyss" + ] + }, "orphaned/Web/API/LinkStyle": { "modified": "2019-03-23T23:29:59.357Z", "contributors": [ @@ -52939,6 +52933,12 @@ "electrolysis" ] }, + "orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { + "modified": "2020-03-12T19:46:14.001Z", + "contributors": [ + "YuichiNukiyama" + ] + }, "orphaned/Web/JavaScript/Reference/Global_Objects/Array/prototype": { "modified": "2020-10-15T21:13:35.051Z", "contributors": [ diff --git a/files/ja/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/ja/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..7b89c66b60 --- /dev/null +++ b/files/ja/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,218 @@ +--- +title: 基本的な概念 +slug: orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +tags: + - Advanced + - IndexedDB + - concepts +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +original_slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +
+

IndexedDB は、ユーザーのブラウザー内にデータを永続的に保存する手段です。ネットワークの状態にかかわらず高度な問い合わせ機能を持つ ウェブアプリケーションを作成できますので、オンラインとオフラインの両方で動作するアプリケーションになります。IndexedDB は大量のデータを保存するアプリケーション (例えばレンタル店の DVD カタログ) や、動作するために持続的なインターネット接続が不要なアプリケーション (例えばメールクライアント、To-Do リスト、メモ帳) で役に立ちます。

+
+ +

このドキュメントについて

+ +

この概論では、IndexedDB の本質的な概念や用語について論じます。これにより全体像を示すとともに、重要な概念を説明します。

+ +

以下の役に立つ項目があります:

+ + + +

IndexedDB の概要

+ +

IndexedDB では、"キー" でインデックス付けされたオブジェクトを保存および取り出すことができます。データベースに対して施したすべての変更は、トランザクションで発生します。たいていの Web ストレージ技術と同様に、IndexedDB も同一生成元ポリシーに従います。よって、保存済みデータは同一ドメイン内からアクセスできますが、異なるドメインにまたがってデータへアクセスすることはできません。

+ +

IndexedDB は、Web Workers を含むほとんどの状況で使用できる非同期 API です。以前は Web Workers で使用するための同期 API も含まれていましたが、Web コミュニティが無関心であったために仕様から削除されました。

+ +

IndexedDB と競合する仕様である WebSQL データベースがありましたが、W3C は 2010 年 11 月 18 日に非推奨にしました。IndexedDB も WebSQL もデータ保存の技術ですが、提供する機能が異なります。WebSQL データベースはリレーショナルデータベースシステムであるのに対して、IndexedDB はインデックス付きのテーブルシステムです。

+ +

重要な概念

+ +

ほかのタイプのデータベースを扱った経験から想定していることがあるなら、IndexedDB を扱うときにはそれを捨てましょう。そして、以下の重要な概念を覚えておいてください:

+ + + +

定義

+ +

この章では、IndexedDB API で使用する用語について定義および説明します。

+ +

データベース

+ +
+
データベース (database)
+
主に 1 個以上のオブジェクトストアで構成される、情報のリポジトリです。それぞれのデータベースが以下のものを持ちます: +
    +
  • 名称。これは特定の生成元に所属するデータベースを識別しており、データベースの存続期間を通じて不変です。名称は任意の文字列値です (空文字列を含む)。
  • +
  • +

    現在のバージョン。始めにデータベースを生成したとき、バージョンは特に指定しない限り整数の 1 になります。それぞれのデータベースは、任意の時点でバージョンを 1 つだけ持ちます。

    +
  • +
+
+
永続性 (durable)
+
+

以前の Firefox では、IndexedDB に永続性がありました。つまり、読み書きトランザクションにおいて、{{domxref("IDBTransaction.oncomplete")}} が発生するのは、すべてのデータがディスク上に実際に書き込まれている(フラッシュされている)ことが保証されたときに限ります。

+ +

Firefox 40 以降、IndexedDB トランザクションはパフォーマンスを向上させるために、永続性の保証を緩和しました ({{Bug("1112702")}} を参照)。これは IndexedDB をサポートする他のブラウザーと同じ動作です。この場合、{{Event("complete")}} イベントは OS がデータの書き込みを指示した時点で発生しますが、実際にはデータがディスク上に反映されていない可能性があります。これによりイベントをより早く発生させられますが、データをディスク上に反映する前に OS のクラッシュや電源断が発生するとトランザクション全体を失う危険性が若干あります。このような破壊的な事象はまれですので、ほとんどの利用者は心配する必要がないでしょう。

+ +
+

注記: Firefox では、何らかの理由 (例えば、後で再計算できない重要なデータを保存する) で永続性を保証したい場合は、実験的 (非標準) な readwriteflush モード ({{domxref("IDBDatabase.transaction")}} を参照) を使用してトランザクションを生成すると、complete イベントを発生させる前にディスクへの反映を強制させることができます。これは現在実験的な扱いであり、about:configdom.indexedDB.experimentaltrue に設定した場合に限り使用できます。

+
+
+
オブジェクトストア (object store)
+
+

データベースにデータを保存する仕組みです。オブジェクトストアはレコードを持続的に保持しており、これはキーと値のペアです。オブジェクトストア内のレコードは、キーによって昇順に整列して保存されています。

+ +

すべてのオブジェクトストアは、データベース内で一意な名称を持たなければなりません。オブジェクトストアは、任意でキージェネレーターキーパスを持つことができます。オブジェクトストアがキーパスを持つ場合は、インラインキーを使用します。それ以外の場合は、アウトオブラインキーを使用します。

+ +

オブジェクトストアのリファレンスドキュメントとして、{{domxref("IDBObjectStore")}} をご覧ください。

+
+
バージョン (version)
+
始めにデータベースを生成したとき、バージョンは整数の 1 になります。それぞれのデータベースは、一度に 1 つのバージョンを持ちます。一度に複数のバージョンを持つことはできません。バージョンを変更する唯一の方法は、現在のバージョンより大きなバージョンでデータベースを開くことです。これは versionchange トランザクションを開始して、upgradeneeded イベントが発生します。データベースのスキーマを更新できる唯一の場所が、このイベントのハンドラ内です。
+
注記: この定義は直近の仕様書で説明されており、最新のブラウザーのみ実装しています。古いブラウザーは非推奨かつ削除済みの IDBDatabase.setVersion() メソッドを実装しています。
+
データベース接続 (database connection)
+
データベースを開くことで生成される操作です。データベースは同時に複数の接続を持つことができます。
+
トランザクション (transaction)
+
+

特定のデータベースで行う、原子性を持つデータアクセスやデータ変更の操作のセットです。これは、データベース内のデータと対話する手段です。実際は、データベース内のデータの読み取りや変更はトランザクション内で実施しなければなりません。

+ +

書き込みトランザクションのスコープが重ならない限り、ひとつのデータベース接続で同時に複数のアクティブなトランザクションが存在できます。トランザクションのスコープは生成時に定義され、トランザクションがどのオブジェクトストアと対話できるかや、トランザクションの持続期間にわたって保持し続けるかを示します。よって例えば、データベース接続で flyingMonkey オブジェクトストアのみ対象とするスコープを持つ書き込みトランザクションがすでに存在するとき、unicornCentaur オブジェクトストアや unicornPegasus オブジェクトストアをスコープで持つ別のトランザクションを開始できます。読み取りトランザクションは、スコープが重なっていても複数実行できます。

+ +

トランザクションは持続期間が短いものを除き、長時間のトランザクションがストレージ資源をロックする状況から解放するために、ブラウザーが終了させることができます。トランザクションは中止させることができ、トランザクションによるデータベースの変更箇所はロールバックされます。また、開始するトランザクションや中止するトランザクションを待つ必要はありません。

+ +

トランザクションには readwritereadonlyversionchange の 3 つのモードがあります。オブジェクトストアやインデックスの生成および削除は、versionchange トランザクションを使用する場合に限り実行できます。トランザクションのタイプについて詳しくは、IndexedDB のリファレンスをご覧ください。

+ +

すべての操作はトランザクション内で発生しますので、トランザクションは IndexedDB の重要な概念です。トランザクションについて、特にバージョニングとの関係については、{{domxref("IDBTransaction")}} および関連ドキュメントをご覧ください。ここにリファレンスドキュメントもあります。

+
+
リクエスト (request)
+
データベースの読み書きを実施する操作です。すべてのリクエストは、ひとつの読み取りまたは書き込みの操作を表します。
+
インデックス (index)
+
+

インデックスは参照先オブジェクトストア (referenced object store)から呼び出されて、別のオブジェクトストアのレコードを検索するための特別なオブジェクトストアです。インデックスは持続的なキーと値のストレージであり、インデックスのレコードの値は、参照先オブジェクトストアのレコードのキーです。インデックス内のレコードは、参照先オブジェクトストアでレコードが挿入、更新、削除されるたびに、自動的に収集されます。インデックス内の各レコードは参照先オブジェクトストア内のレコードをひとつだけ示すことができますが、複数のインデックスが同一のオブジェクトストアを参照することもできます。オブジェクトストアが変更されると、そのオブジェクトストアを参照するすべてのインデックスが自動的に更新されます。

+ +

代わりに、キーを使用してオブジェクトストア内のレコードを検索することもできます。

+ +

インデックスの使用法について詳しくは、IndexedDB を使用するをご覧ください。インデックスのリファレンスドキュメントとして、IDBKeyRange をご覧ください。

+
+
+ +

キーと

+ +
+
キー (key)
+
+

オブジェクトストアに保存された値は、このデータ値によって編成および取り出しされます。オブジェクトストアはキージェネレーターキーパス、明示的に指定した値の、3 種類の生成源のいずれかからキーを得られます。キーは、自身の前にあるものより大きな数値を持つデータ型であることが必要です。オブジェクトストア内の各レコードはオブジェクトストア内で一意のキーを持たなければならず、オブジェクトストア内で複数のレコードが同じキーを持つことはできません。

+ +

キーは 文字列date、浮動小数点数値、配列のいずれかの型を使用できます。配列では、キーは空の値から無限大までの範囲を使用できます。また、配列の中に配列を含めることができます。文字列または整数値のキーしか使用できないという条件はありません。

+ +

代わりに、インデックスを使用してオブジェクトストア内のレコードを検索することもできます。

+
+
キージェネレーター (key generator)
+
指定した順序で新たなキーを生成する仕組みです。オブジェクトストアがキージェネレーターを持たない場合は、保存するレコードのキーをアプリケーションが提供しなければなりません。ジェネレーターはストア間で共有しません。これはむしろブラウザーの実装の細部であり、Web 開発において実際にはキージェネレーターの生成やアクセスは行いません。
+
インラインキー (in-line key)
+
保存される値の一部として保存されるキーです。これはキーパスを使用して見つけます。インラインキーは、ジェネレーターを使用して生成できます。キーが生成されると、キーパスを使用してキーを値の中に保存したり、キーとして使用したりすることができます。
+
アウトオブラインキー (out-of-line key)
+
保存する値とは別に保存されるキーです。
+
キーパス (key path)
+
オブジェクトストアやインデックスのどこからブラウザーがキーを取り出すべきかを定義します。有効なキーパスは空文字列、JavaScript の識別子、ピリオドで区切られた複数の JavaScript の識別子、あるいはそれらを収めた配列のいずれかを含むことができます。空白を含むことはできません。
+
値 (value)
+
+

それぞれのレコードは値を持っており、論理値数値文字列dateオブジェクト配列正規表現undefined、null を含む、JavaScript で表現可能なものをどれでも含むことができます。

+ +

オブジェクトまたは配列を保存する場合は、それらのプロパティや値もまた、有効な値をどれでも持つことができます。

+ +

また、Blob やファイルも保存可能です。仕様書 をご覧ください。

+
+
+ +

レンジとスコープ

+ +
+
スコープ (scope)
+
トランザクションの適用先であるオブジェクトストアやインデックスのセットです。読み取りのみのトランザクションのスコープは、同時に重ね合ったり実行することができます。一方、書き込みトランザクションのスコープは重ね合うことができません。同時に同一のスコープで複数のトランザクションを開始することはできますが、それらはキューに収められ、順番に実行されます。
+
カーソル (cursor)
+
キーレンジに属する複数のレコードにわたって反復処理を行うための仕組みです。カーソルは、反復処理を行うインデックスやオブジェクトストアがどれかを示す source を持ちます。またレンジ内の位置や、レコードキーの順序について増加方向に移動しているか減少方向に移動しているかの情報も持ちます。カーソルのリファレンスドキュメントとして、IDBCursorIDBCursorSync をご覧ください。
+
キーレンジ (key range)
+
+

キーとして使用する、何らかのデータ型の連続的な区間です。キーまたはキーレンジを使用して、オブジェクトストアやインデックスからレコードを取り出すことができます。下限または上限を使用して、レンジを制限またはフィルターリングできます。例えばキーが x から y の間であるすべての値に対して、反復処理を行うことができます。

+ +

キーレンジのリファレンスドキュメントとして、{{domxref("IDBKeyRange")}} をご覧ください。

+
+
+ +

制限

+ +

IndexedDB は、クライアントサイドのストレージが必要なほとんどのケースに対応します。しかし、以下のような一部のケースに対して設計されてはいません:

+ + + +

加えて、以下のような状況でブラウザーがデータベースを削除する場合があることを意識してください:

+ + + +

正確な状況やブラウザーの機能は時間とともに変化しますが、ブラウザーベンダーの一般的な考え方は、可能な限りデータを維持するよう最大限に努力することです。

+ +

次のステップ

+ +

主要な概念を習得したら、より具体的なことを学べるようになります。API の使用方法に関するチュートリアルである、IndexedDB を使用するをご覧ください。

+ +

関連情報

+ + diff --git a/files/ja/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/ja/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html new file mode 100644 index 0000000000..b02af7aa13 --- /dev/null +++ b/files/ja/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html @@ -0,0 +1,78 @@ +--- +title: 'TypeError: invalid arguments' +slug: orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +tags: + - Error + - Errors + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +original_slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +--- +
{{jsSidebar("Errors")}}
+ +

メッセージ

+ +
TypeError: invalid arguments (Firefox)
+ +

エラータイプ

+ +

{{jsxref("TypeError")}}

+ +

何がうまくいかなかったのか?

+ +

新しい typed array を生成するために、Typed array コンストラクターに以下のいずれかの値を渡す必要があります。

+ + + +

そのほかのコンストラクター引数では、有効な typed array を生成できません。

+ +

+ +

Typed array、たとえば {{jsxref("Uint8Array")}} は文字列から構成できません。事実、文字列はまったく typed array にすることはできません。

+ +
var ta = new Uint8Array("nope");
+// TypeError: invalid arguments
+
+ +

有効な {{jsxref("Uint8Array")}} を生成するほかの方法:

+ +
// From a length
+var uint8 = new Uint8Array(2);
+uint8[0] = 42;
+console.log(uint8[0]); // 42
+console.log(uint8.length); // 2
+console.log(uint8.BYTES_PER_ELEMENT); // 1
+
+// From an array
+var arr = new Uint8Array([21,31]);
+console.log(arr[1]); // 31
+
+// From another TypedArray
+var x = new Uint8Array([21, 31]);
+var y = new Uint8Array(x);
+console.log(y[0]); // 21
+
+// From an ArrayBuffer
+var buffer = new ArrayBuffer(8);
+var z = new Uint8Array(buffer, 1, 4);
+
+// From an iterable
+var iterable = function*(){ yield* [1,2,3]; }();
+var uint8 = new Uint8Array(iterable);
+// Uint8Array[1, 2, 3]
+
+ +

関連項目

+ + diff --git a/files/ja/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/ja/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html deleted file mode 100644 index d155ad6fef..0000000000 --- a/files/ja/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html +++ /dev/null @@ -1,217 +0,0 @@ ---- -title: 基本的な概念 -slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -tags: - - Advanced - - IndexedDB - - concepts -translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB ---- -

{{DefaultAPISidebar("IndexedDB")}}

- -
-

IndexedDB は、ユーザーのブラウザー内にデータを永続的に保存する手段です。ネットワークの状態にかかわらず高度な問い合わせ機能を持つ ウェブアプリケーションを作成できますので、オンラインとオフラインの両方で動作するアプリケーションになります。IndexedDB は大量のデータを保存するアプリケーション (例えばレンタル店の DVD カタログ) や、動作するために持続的なインターネット接続が不要なアプリケーション (例えばメールクライアント、To-Do リスト、メモ帳) で役に立ちます。

-
- -

このドキュメントについて

- -

この概論では、IndexedDB の本質的な概念や用語について論じます。これにより全体像を示すとともに、重要な概念を説明します。

- -

以下の役に立つ項目があります:

- - - -

IndexedDB の概要

- -

IndexedDB では、"キー" でインデックス付けされたオブジェクトを保存および取り出すことができます。データベースに対して施したすべての変更は、トランザクションで発生します。たいていの Web ストレージ技術と同様に、IndexedDB も同一生成元ポリシーに従います。よって、保存済みデータは同一ドメイン内からアクセスできますが、異なるドメインにまたがってデータへアクセスすることはできません。

- -

IndexedDB は、Web Workers を含むほとんどの状況で使用できる非同期 API です。以前は Web Workers で使用するための同期 API も含まれていましたが、Web コミュニティが無関心であったために仕様から削除されました。

- -

IndexedDB と競合する仕様である WebSQL データベースがありましたが、W3C は 2010 年 11 月 18 日に非推奨にしました。IndexedDB も WebSQL もデータ保存の技術ですが、提供する機能が異なります。WebSQL データベースはリレーショナルデータベースシステムであるのに対して、IndexedDB はインデックス付きのテーブルシステムです。

- -

重要な概念

- -

ほかのタイプのデータベースを扱った経験から想定していることがあるなら、IndexedDB を扱うときにはそれを捨てましょう。そして、以下の重要な概念を覚えておいてください:

- - - -

定義

- -

この章では、IndexedDB API で使用する用語について定義および説明します。

- -

データベース

- -
-
データベース (database)
-
主に 1 個以上のオブジェクトストアで構成される、情報のリポジトリです。それぞれのデータベースが以下のものを持ちます: -
    -
  • 名称。これは特定の生成元に所属するデータベースを識別しており、データベースの存続期間を通じて不変です。名称は任意の文字列値です (空文字列を含む)。
  • -
  • -

    現在のバージョン。始めにデータベースを生成したとき、バージョンは特に指定しない限り整数の 1 になります。それぞれのデータベースは、任意の時点でバージョンを 1 つだけ持ちます。

    -
  • -
-
-
永続性 (durable)
-
-

以前の Firefox では、IndexedDB に永続性がありました。つまり、読み書きトランザクションにおいて、{{domxref("IDBTransaction.oncomplete")}} が発生するのは、すべてのデータがディスク上に実際に書き込まれている(フラッシュされている)ことが保証されたときに限ります。

- -

Firefox 40 以降、IndexedDB トランザクションはパフォーマンスを向上させるために、永続性の保証を緩和しました ({{Bug("1112702")}} を参照)。これは IndexedDB をサポートする他のブラウザーと同じ動作です。この場合、{{Event("complete")}} イベントは OS がデータの書き込みを指示した時点で発生しますが、実際にはデータがディスク上に反映されていない可能性があります。これによりイベントをより早く発生させられますが、データをディスク上に反映する前に OS のクラッシュや電源断が発生するとトランザクション全体を失う危険性が若干あります。このような破壊的な事象はまれですので、ほとんどの利用者は心配する必要がないでしょう。

- -
-

注記: Firefox では、何らかの理由 (例えば、後で再計算できない重要なデータを保存する) で永続性を保証したい場合は、実験的 (非標準) な readwriteflush モード ({{domxref("IDBDatabase.transaction")}} を参照) を使用してトランザクションを生成すると、complete イベントを発生させる前にディスクへの反映を強制させることができます。これは現在実験的な扱いであり、about:configdom.indexedDB.experimentaltrue に設定した場合に限り使用できます。

-
-
-
オブジェクトストア (object store)
-
-

データベースにデータを保存する仕組みです。オブジェクトストアはレコードを持続的に保持しており、これはキーと値のペアです。オブジェクトストア内のレコードは、キーによって昇順に整列して保存されています。

- -

すべてのオブジェクトストアは、データベース内で一意な名称を持たなければなりません。オブジェクトストアは、任意でキージェネレーターキーパスを持つことができます。オブジェクトストアがキーパスを持つ場合は、インラインキーを使用します。それ以外の場合は、アウトオブラインキーを使用します。

- -

オブジェクトストアのリファレンスドキュメントとして、{{domxref("IDBObjectStore")}} をご覧ください。

-
-
バージョン (version)
-
始めにデータベースを生成したとき、バージョンは整数の 1 になります。それぞれのデータベースは、一度に 1 つのバージョンを持ちます。一度に複数のバージョンを持つことはできません。バージョンを変更する唯一の方法は、現在のバージョンより大きなバージョンでデータベースを開くことです。これは versionchange トランザクションを開始して、upgradeneeded イベントが発生します。データベースのスキーマを更新できる唯一の場所が、このイベントのハンドラ内です。
-
注記: この定義は直近の仕様書で説明されており、最新のブラウザーのみ実装しています。古いブラウザーは非推奨かつ削除済みの IDBDatabase.setVersion() メソッドを実装しています。
-
データベース接続 (database connection)
-
データベースを開くことで生成される操作です。データベースは同時に複数の接続を持つことができます。
-
トランザクション (transaction)
-
-

特定のデータベースで行う、原子性を持つデータアクセスやデータ変更の操作のセットです。これは、データベース内のデータと対話する手段です。実際は、データベース内のデータの読み取りや変更はトランザクション内で実施しなければなりません。

- -

書き込みトランザクションのスコープが重ならない限り、ひとつのデータベース接続で同時に複数のアクティブなトランザクションが存在できます。トランザクションのスコープは生成時に定義され、トランザクションがどのオブジェクトストアと対話できるかや、トランザクションの持続期間にわたって保持し続けるかを示します。よって例えば、データベース接続で flyingMonkey オブジェクトストアのみ対象とするスコープを持つ書き込みトランザクションがすでに存在するとき、unicornCentaur オブジェクトストアや unicornPegasus オブジェクトストアをスコープで持つ別のトランザクションを開始できます。読み取りトランザクションは、スコープが重なっていても複数実行できます。

- -

トランザクションは持続期間が短いものを除き、長時間のトランザクションがストレージ資源をロックする状況から解放するために、ブラウザーが終了させることができます。トランザクションは中止させることができ、トランザクションによるデータベースの変更箇所はロールバックされます。また、開始するトランザクションや中止するトランザクションを待つ必要はありません。

- -

トランザクションには readwritereadonlyversionchange の 3 つのモードがあります。オブジェクトストアやインデックスの生成および削除は、versionchange トランザクションを使用する場合に限り実行できます。トランザクションのタイプについて詳しくは、IndexedDB のリファレンスをご覧ください。

- -

すべての操作はトランザクション内で発生しますので、トランザクションは IndexedDB の重要な概念です。トランザクションについて、特にバージョニングとの関係については、{{domxref("IDBTransaction")}} および関連ドキュメントをご覧ください。ここにリファレンスドキュメントもあります。

-
-
リクエスト (request)
-
データベースの読み書きを実施する操作です。すべてのリクエストは、ひとつの読み取りまたは書き込みの操作を表します。
-
インデックス (index)
-
-

インデックスは参照先オブジェクトストア (referenced object store)から呼び出されて、別のオブジェクトストアのレコードを検索するための特別なオブジェクトストアです。インデックスは持続的なキーと値のストレージであり、インデックスのレコードの値は、参照先オブジェクトストアのレコードのキーです。インデックス内のレコードは、参照先オブジェクトストアでレコードが挿入、更新、削除されるたびに、自動的に収集されます。インデックス内の各レコードは参照先オブジェクトストア内のレコードをひとつだけ示すことができますが、複数のインデックスが同一のオブジェクトストアを参照することもできます。オブジェクトストアが変更されると、そのオブジェクトストアを参照するすべてのインデックスが自動的に更新されます。

- -

代わりに、キーを使用してオブジェクトストア内のレコードを検索することもできます。

- -

インデックスの使用法について詳しくは、IndexedDB を使用するをご覧ください。インデックスのリファレンスドキュメントとして、IDBKeyRange をご覧ください。

-
-
- -

キーと

- -
-
キー (key)
-
-

オブジェクトストアに保存された値は、このデータ値によって編成および取り出しされます。オブジェクトストアはキージェネレーターキーパス、明示的に指定した値の、3 種類の生成源のいずれかからキーを得られます。キーは、自身の前にあるものより大きな数値を持つデータ型であることが必要です。オブジェクトストア内の各レコードはオブジェクトストア内で一意のキーを持たなければならず、オブジェクトストア内で複数のレコードが同じキーを持つことはできません。

- -

キーは 文字列date、浮動小数点数値、配列のいずれかの型を使用できます。配列では、キーは空の値から無限大までの範囲を使用できます。また、配列の中に配列を含めることができます。文字列または整数値のキーしか使用できないという条件はありません。

- -

代わりに、インデックスを使用してオブジェクトストア内のレコードを検索することもできます。

-
-
キージェネレーター (key generator)
-
指定した順序で新たなキーを生成する仕組みです。オブジェクトストアがキージェネレーターを持たない場合は、保存するレコードのキーをアプリケーションが提供しなければなりません。ジェネレーターはストア間で共有しません。これはむしろブラウザーの実装の細部であり、Web 開発において実際にはキージェネレーターの生成やアクセスは行いません。
-
インラインキー (in-line key)
-
保存される値の一部として保存されるキーです。これはキーパスを使用して見つけます。インラインキーは、ジェネレーターを使用して生成できます。キーが生成されると、キーパスを使用してキーを値の中に保存したり、キーとして使用したりすることができます。
-
アウトオブラインキー (out-of-line key)
-
保存する値とは別に保存されるキーです。
-
キーパス (key path)
-
オブジェクトストアやインデックスのどこからブラウザーがキーを取り出すべきかを定義します。有効なキーパスは空文字列、JavaScript の識別子、ピリオドで区切られた複数の JavaScript の識別子、あるいはそれらを収めた配列のいずれかを含むことができます。空白を含むことはできません。
-
値 (value)
-
-

それぞれのレコードは値を持っており、論理値数値文字列dateオブジェクト配列正規表現undefined、null を含む、JavaScript で表現可能なものをどれでも含むことができます。

- -

オブジェクトまたは配列を保存する場合は、それらのプロパティや値もまた、有効な値をどれでも持つことができます。

- -

また、Blob やファイルも保存可能です。仕様書 をご覧ください。

-
-
- -

レンジとスコープ

- -
-
スコープ (scope)
-
トランザクションの適用先であるオブジェクトストアやインデックスのセットです。読み取りのみのトランザクションのスコープは、同時に重ね合ったり実行することができます。一方、書き込みトランザクションのスコープは重ね合うことができません。同時に同一のスコープで複数のトランザクションを開始することはできますが、それらはキューに収められ、順番に実行されます。
-
カーソル (cursor)
-
キーレンジに属する複数のレコードにわたって反復処理を行うための仕組みです。カーソルは、反復処理を行うインデックスやオブジェクトストアがどれかを示す source を持ちます。またレンジ内の位置や、レコードキーの順序について増加方向に移動しているか減少方向に移動しているかの情報も持ちます。カーソルのリファレンスドキュメントとして、IDBCursorIDBCursorSync をご覧ください。
-
キーレンジ (key range)
-
-

キーとして使用する、何らかのデータ型の連続的な区間です。キーまたはキーレンジを使用して、オブジェクトストアやインデックスからレコードを取り出すことができます。下限または上限を使用して、レンジを制限またはフィルターリングできます。例えばキーが x から y の間であるすべての値に対して、反復処理を行うことができます。

- -

キーレンジのリファレンスドキュメントとして、{{domxref("IDBKeyRange")}} をご覧ください。

-
-
- -

制限

- -

IndexedDB は、クライアントサイドのストレージが必要なほとんどのケースに対応します。しかし、以下のような一部のケースに対して設計されてはいません:

- - - -

加えて、以下のような状況でブラウザーがデータベースを削除する場合があることを意識してください:

- - - -

正確な状況やブラウザーの機能は時間とともに変化しますが、ブラウザーベンダーの一般的な考え方は、可能な限りデータを維持するよう最大限に努力することです。

- -

次のステップ

- -

主要な概念を習得したら、より具体的なことを学べるようになります。API の使用方法に関するチュートリアルである、IndexedDB を使用するをご覧ください。

- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/ja/web/javascript/reference/errors/typed_array_invalid_arguments/index.html deleted file mode 100644 index b1c8d14d35..0000000000 --- a/files/ja/web/javascript/reference/errors/typed_array_invalid_arguments/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: 'TypeError: invalid arguments' -slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments -tags: - - Error - - Errors - - JavaScript - - TypeError -translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments ---- -
{{jsSidebar("Errors")}}
- -

メッセージ

- -
TypeError: invalid arguments (Firefox)
- -

エラータイプ

- -

{{jsxref("TypeError")}}

- -

何がうまくいかなかったのか?

- -

新しい typed array を生成するために、Typed array コンストラクターに以下のいずれかの値を渡す必要があります。

- - - -

そのほかのコンストラクター引数では、有効な typed array を生成できません。

- -

- -

Typed array、たとえば {{jsxref("Uint8Array")}} は文字列から構成できません。事実、文字列はまったく typed array にすることはできません。

- -
var ta = new Uint8Array("nope");
-// TypeError: invalid arguments
-
- -

有効な {{jsxref("Uint8Array")}} を生成するほかの方法:

- -
// From a length
-var uint8 = new Uint8Array(2);
-uint8[0] = 42;
-console.log(uint8[0]); // 42
-console.log(uint8.length); // 2
-console.log(uint8.BYTES_PER_ELEMENT); // 1
-
-// From an array
-var arr = new Uint8Array([21,31]);
-console.log(arr[1]); // 31
-
-// From another TypedArray
-var x = new Uint8Array([21, 31]);
-var y = new Uint8Array(x);
-console.log(y[0]); // 21
-
-// From an ArrayBuffer
-var buffer = new ArrayBuffer(8);
-var z = new Uint8Array(buffer, 1, 4);
-
-// From an iterable
-var iterable = function*(){ yield* [1,2,3]; }();
-var uint8 = new Uint8Array(iterable);
-// Uint8Array[1, 2, 3]
-
- -

関連項目

- - diff --git a/files/ko/_redirects.txt b/files/ko/_redirects.txt index 9340068327..5cb2285f1b 100644 --- a/files/ko/_redirects.txt +++ b/files/ko/_redirects.txt @@ -328,7 +328,7 @@ /ko/docs/HTML:Element:a /ko/docs/Web/HTML/Element/a /ko/docs/HTML:Inline_elements /ko/docs/Web/HTML/Inline_elements /ko/docs/IndexedDB /ko/docs/Web/API/IndexedDB_API -/ko/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /ko/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/ko/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /ko/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /ko/docs/IndexedDB/Using_IndexedDB /ko/docs/Web/API/IndexedDB_API/Using_IndexedDB /ko/docs/Introduction_to_using_XPath_in_JavaScript /ko/docs/Web/XPath/Introduction_to_using_XPath_in_JavaScript /ko/docs/JSAPI_Reference/Alphabetical_List /ko/docs/JSAPI_Reference @@ -626,6 +626,7 @@ /ko/docs/Web/API/HTMLHyperlinkElementUtils/href /ko/docs/Web/API/HTMLAnchorElement/href /ko/docs/Web/API/HTML_드래그_앤_드롭_API /ko/docs/Web/API/HTML_Drag_and_Drop_API /ko/docs/Web/API/HTML_드래그_앤_드롭_API/Drag_operations /ko/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations +/ko/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /ko/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /ko/docs/Web/API/Navigator.battery /ko/docs/Web/API/Navigator/battery /ko/docs/Web/API/Navigator.battery/window.navigator.battery /ko/docs/Web/API/Navigator/battery /ko/docs/Web/API/Navigator.connection/window.navigator.connection /ko/docs/Web/API/Navigator/connection diff --git a/files/ko/_wikihistory.json b/files/ko/_wikihistory.json index bb0efda708..4322628e68 100644 --- a/files/ko/_wikihistory.json +++ b/files/ko/_wikihistory.json @@ -5594,21 +5594,6 @@ "claudepache" ] }, - "Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { - "modified": "2020-12-08T00:45:03.205Z", - "contributors": [ - "dsma73", - "chrisdavidmills", - "alattalatta", - "LostCatLee", - "daesD", - "naduhy2", - "bingl2", - "nacyot", - "fscholz", - "JoonghunPark" - ] - }, "Web/API/IndexedDB_API/Using_IndexedDB": { "modified": "2020-07-21T23:16:52.351Z", "contributors": [ @@ -18367,6 +18352,21 @@ "connorshea" ] }, + "orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { + "modified": "2020-12-08T00:45:03.205Z", + "contributors": [ + "dsma73", + "chrisdavidmills", + "alattalatta", + "LostCatLee", + "daesD", + "naduhy2", + "bingl2", + "nacyot", + "fscholz", + "JoonghunPark" + ] + }, "orphaned/Web/API/OffscreenCanvas/toBlob": { "modified": "2020-10-15T22:14:42.795Z", "contributors": [ diff --git a/files/ko/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/ko/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..637c74a373 --- /dev/null +++ b/files/ko/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,224 @@ +--- +title: 기본 개념 +slug: orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +tags: + - Advanced + - IndexedDB +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +original_slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +
+

IndexedDB는 사용자의 브라우저 안에 데이터를 영구적으로 저장하게 해주는 방법 중 하나입니다. 그것은 네트워크 가능 여부에 상관없이, 풍부한 쿼리 작성 능력으로 웹 애플리케이션을 만들게 해주고, 이 애플리케이션은 온라인과 오프라인 모두에서 동작할 수 있습니다. IndexedDB는 예를 들면, 도서관의 DVD 목록처럼 대용량 데이터를 저장하는 애플리케이션, 그리고 메일 클라이언트, to-do 리스트, 노트패드처럼 동작에 지속적인 인터넷 연결이 필요하지 않은 애플리케이션에 유용합니다.

+
+ +

이 문서에 대하여

+ +

이 소개글은 IndexedDB의 필수 개념과 용어에 대해 논의합니다. 큰 그림을 제공하고 핵심 개념들을 설명합니다.

+ +

다음과 같은 유용한 정보를 찾을 수 있을 것입니다.

+ + + +

IndexedDB 개요

+ +

IndexedDB는 "키(key)"로 지정된 객체를 저장하고 검색할 수 있도록 도와줍니다. 데이터베이스에 적용하는 모든 변경은 트렌잭션 안에서 일어납니다. 대부분의 웹 스토리지 솔루션과 마찬가지로, IndexedDB는 동일 출처 정책 (same-origin policy)을 따릅니다. 따라서 당신이 한 도메인의 데이터에 접근하고 있는 동안, 다른 도메인의 데이터에 접근할 수 없습니다.

+ +

IndexedDB는 웹 워커를 포함하는 대부분의 문맥(컨텍스트)에 사용될 수 있는 비동기(asynchronous) API입니다. 웹 워커에서 사용하기 위해 동기(synchronous) 버전도 존재했지만, 웹 커뮤니티의 관심부족으로 웹 스펙에서 제거되었습니다.

+ +

IndexedDB는 WebSQL 데이터베이스와 경쟁 관계에 있었지만, W3C는 2010 11월 8일에 WebSQL을 폐기(deprecated)하였습니다. IndexedDB와 WebSQL 모두 데이터 저장을 위한 솔루션이지만, 동일한 기능을 제공하지는 않습니다. WebSQL Database는 관계형 데이터베이스 접근 시스템인 반면, IndexedDB는 인덱스 테이블 시스템입니다.

+ +

주요 개념들

+ +

만약 당신이 다른 DB 시스템을 사용해봤던 경험이 있다면 오히려 잘못된 추측으로 인해 IndexedDB로 작업할 때 힘들어질 수도 있습니다. 그러므로 다음의 중요한 개념들을 잘 정리해 두어야 합니다.

+ + + +

정의

+ +

이 섹션은 IndexedDB API에서 사용되는 용어들을 정의하고 설명합니다.

+ +

데이터베이스

+ +
+
데이터베이스
+
일반적으로 하나 혹은 그 이상의 객체 저장소로 구성되는 정보의 레파지토리입니다. 개별 데이터베이스는 다음의 내용을 반드시 가져야 합니다. +
    +
  • 이름(Name). 이것은 하나의 특정 출처 내에서 database를 구별하고 데이터베이스가 존재하는 동안 일정하게 유지됩니다. 이름은 빈 문자열을 포함해서 어떤 문자열 값이라도 될 수 있습니다.
  • +
  • +

    현재 버전. 데이터베이스가 처음 만들어질 때, 따로 지정하지 않으면 버전은 정수 1입니다. 각 데이터베이스는 주어진 순간에 오직 하나의 버전을 가질 수 있습니다.

    +
  • +
+
+
지속성
+
+

파이어폭스에서 indexedDB는 지속성을 유지하기 위해 사용됩니다. 즉, 읽기쓰기 트랜젝션{{domxref("IDBTransaction.oncomplete")}}이 모든 데이터가 디스크로 들어갈 수 있도록 보장될 때에만 실행됩니다.

+ +

파이어폭스 40에서, IndexedDB 트랜젝션은 성능을 높이기 위해 지속성 보장을 늦춰왔는데, 이는 IndexedDB를 지원하는 다른 브라우저도 동일한 방식입니다{{Bug("1112702")}}. 이 경우 {{Event("complete")}} 이벤트는 OS가 데이터 쓰기를 하라고 전달한 후, 데이터가 실제로 데이터베이스에 반영되기 전에 잠재적으로 실행됩니다. 이벤트는 이전보다 더 빠르게 전달될지도 모르지만, 만약 OS가 다운되거나 데이터가 데이터베이스에 반영되기 전에 시스템 전원이 부족하면, 전체 트랜젝션은 잃게 될 수도 있는 희박한 위험성이 존재합니다. 그런 치명적인 이벤트는 드물기 때문에, 대부분의 소비자는 더 이상 염려할 필요는 없습니다.

+ +
+

Note: 파이어폭스에서 (나중에 다시 계산 할 수 없는 까다로운 데이터를 저장하는 것)과 같은 몇 가지 이유로 지속성을 보장하고 싶다면, complete 이벤트가 전달되기 전에 아직 정식 표준이 아닌 실험적인 readwriteflush 모드를 이용하여 트랜젝션을 데이터베이스에 강제로 반영할 수 있습니다. ({{domxref("IDBDatabase.transaction")}} 참고.) 현재는 실험적으로 적용되어 있고(experimental), about:config에서dom.indexedDB.experimental값이 true 로 설정되어 있을 때만 사용할 수 있습니다.

+
+
+
객체 저장소 ( Object Store )
+
+

데이터베이스에 데이터가 저장되는 매커니즘입니다. 객체 저장소는 키(key)와 값(value)의 쌍으로 된 레코드를 영구적으로 잡습니다. 한 객체 저장소 안의 레코드는 키(key)에 따라 오름차순으로 정렬됩니다.

+ +

모든 객체 저장소는 데이터베이스 안에서 고유한 이름을 가져야 합니다. 객체 저장소는 선택적으로 key generatorkey path를 가질 수 있습니다. 만약 객체 저장소가 key path를 가진다면, 그것은 in-line keys를 사용합니다.  아니면, 그것은 out-of-line keys를 사용하는 것입니다.

+ +

객체 저장소에 대한 보다 자세한 정보는, IDBObjectStore 또는 IDBObjectStoreSync를 참조하세요.

+
+
version
+
Database가 처음 만들어질 때, version은 정수형 숫자로 1입니다. 각 database는  하나의 version을 집니다; 하나의 데이터베이스가 한번에 여러 version으로 존재할 수 없다. version을 바꾸는 유일한 방법은 현재 버전보다 큰 버전으로 그것을 여는 것입니다. 이렇ㄱ하면 versionchange 트랜잭션을 시작하고 upgradeneeded event를 발생시킵니다. database의 schema를 변경하려면 upgradeneed 이벤트 핸들러내에서 수행해야 합니다.
+
Note: 이 스펙은  most recent specification, which is only implemented in up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
+
database connection
+
 database를 여는 것에 의해 생성되는 operation. 한 주어진 database는 동시에 여러개의 connections를 가질 수 있다.
+
transaction
+
+

특정 database에 대한 data-access와 data-modification operations의 원자적이고 견고한 집합. 그것이 database에서 당신이 data로 상호작용하는 방법이다. 사실, database에서의 어떠한 data의 읽기 또는 변경도 transaction 내에서 일어나야 한다.

+ +

하나의 database connection은 한번에 그에 연관된 여러 active transaction을 가질 수 있다, writing transactions이 겹치는 scopes을 갖지 않는 동안. 생성에서 정의되는  transactions의 scope은 그 transaction이 어느 object stores와 상호작용할 수 있는지를 결정하고 그 transaction의 lifetime동안 일정하다. 따라서, 예를 들어, 만약 한 database connection이 flyingMonkey object store를 커버하는 scope의 writing transaction을 이미 가지면, 당신은  unicornCentaur과 unicornPegasus object stores의 scope을 가진 두번째 transaction을 시작할 수 있다. reading transactions로서, 당신은 여러개를 가질 수 있다 — 심지어 겹치는 것들이라도.

+ +

Transactions는 short-lived일 것이 기대된다, 그래서 브라우저는 너무 오래걸리는 transaction을 종료할 수 있다, 그 long-running transaction이 lock한 storage resources를 해제하기 위해. 당신은 transaction을 abort할 수 있다 , 이는 그 transaction에서 만들어진 변경들을 roll back한다. 그리고 당신은 심지어 transaction을 abort하기 위해 그것이 시작되거나 활성화되기를 기다릴 필요가 없다.

+ +

Transaction의 세가지 모드는: readwrite, readonly, 그리고 versionchange. Object stores와 indexes를 생성하는 유일한 방법은 versionchange transaction을 이용하는 것이다. transaction types를 더 배우기 위해, IndexedDB에 대한 reference article을 보라.

+ +

모든 것은 하나의 transaction에서 일어나기 때문에, IndexedDB에서 그것은 매우 중요한 개념이다. transactions에 대해 더 배우기 위해, 특히 그것들이 어떻게 versioning과 관련되는가에 대해, IDBTransaction를 보라, 그는 또한 reference documentation을 가진다. synchronous API에 대한 문서를 위해, IDBTransactionSync를 보라.

+
+
request
+
database에 읽고 쓰기를 행하는 operation. 모든 request는 하나의 읽기 혹은 쓰기 operation을 나타낸다.
+
index
+
+

하나의 index는 다른 object store의 records를 찾기 위한 specialized object store이다, referenced object store라 불리는. index는 그 records의 value part가 referenced object store의 한 record의 key part인 영구적인 key-value storage이다. 하나의 index의 records는 referenced object안에 record가 삽입되고 update되고 삭제될 때마다 자동적으로 생성된다. 하나의 index의 각 record는 그의 referenced object store의 오직 하나의 record를 가리킬 수 있다, 그러나 여러 indexes가 같은 object store를 참조할 수 있다. object store가 변할 때, 그 object store를 참조하는 모든 index는 자동으로 update된다.

+ +

다른 방법으로, key를 사용해서 object store에서 records를 찾을 수 있다.

+ +

indexes 사용하기에 대해 더 배우기 위해, Using IndexedDB를 보라. index에 대한 reference documentation을 위해, IDBKeyRange를 보라.

+
+
+ +

Key and value

+ +
+
key
+
+

object store에서 이에 의해 저장된 values가 조직되고 조회되는 하나의 data value. object store는 세 sources 중 하나로부터 key를 이끌어낼 수 있다: key generatorkey path, 또는 명시적으로 지정된 value. key는 그 앞에 있는 것보다 큰 값을 지닌 한 data type의 것이어야 한다. object store의 각 record는 같은 store 내에서 유일한 key를 가져야 한다, 따라서 당신은 주어진 object store에서 같은 key의 여러 records를 가질 수 없다.

+ +

하나의 key는 다음의 types 중 하나가 될 수 있다: string, date, float, 그리고 array. arrays에 대해, key는 empty value로부터 infinity의 범위가 될 수 있다. 그리고 당신은 array 내에 array를 포함할 수 있다. string 또는 integer의 key만 사용해야 한다는 요구사항은 없다.

+ +

다른 방법으로, 당신은 index를 사용해서 object store에서 records를 찾을 수 있다.

+
+
key generator
+
정렬 sequence로 새 keys를 생성하기 위한 mechanism. 만약 한 object store가 key generator를 가지지 않으면, application은 저장되는 records를 위한 keys를 제공해야 한다. Generators는 stores 간에 공유되지 않는다. 이것은 브라우저 구현 세부사항에 가깝다, 때문에 web 개발에서, 당신은 실제로 key generators를 만들고 접근할 필요가 없다.
+
in-line key
+
저장되는 value의 부분으로서 저장되는 key. key path를 사용함으로써 찾아진다. 하나의 in-line key는 generator를 이용해서 생성될 수 있다. key가 생성된 후에, 그것은 key path를 사용하는 value에 저장될 수 있거나 key로서 사용될 수 있다.
+
out-of-line key
+
저장되는 value와는 따로 저장되는 key.
+
key path
+
object store 또는 index에서 브라우저가 어디로부터 key를 추출해야 하는지 정의한다. 하나의 valid key path는 다음 중 하나를 포함할 수 있다: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods. 그것은 spaces를 포함할 수 없다.
+
value
+
+

각각의 record는 하나의 value를 가진다, 이는 javascript로 표현될 수 있는 어떤 것이라도 포함할 수 있다, boolean, number, string, date, object, array, regexp, undefined, 그리고 null을 포함해서.

+ +

object 또는 array가 저장될 때, 그 object 또는 array의  properties 와 values는 적합한 어떤 값이라도 될 수 있다.

+ +

Blobs와 files가 저장될 수 있다, cf. specification.

+
+
+ +

Range and scope

+ +
+
scope
+
한 transaction이 적용되는 object stores와 indexe. read-only transactions의 scope은 겹칠 수 있고 동시에 실행될 수 있다. 한편으로, writing transactions의 scope은 겹칠 수 없다. 당신은 여전히 동시에 같은 scope의 여러 transaction을 실행할 수 있지만 그들은 queue up하고 하나하나 차례로 실행된다.
+
cursor
+
한 key range의 여러 records에 대한 iterating을 위한 mechanism. The cursor는 그것이 iterating하는 것이 어느 index또는 object store인지 가리키는 한 source를 가진다. 그것은 그 range 내의 position을 가지고, record keys의 순서에서 증가 혹은 감소하는 한 방향으로 움직인다. cursors에 대한 reference documentation을 위해, IDBCursor 또는 IDBCursorSync를 보라.
+
key range
+
+

keys를 위해 사용되는 몇몇 data type에 대한 하나의 연속 구간. Records는 keys 또는 하나의 range of keys를 사용하는 object sotres와 indexes로부터 조회될 수 있다. 당신은 lower 그리고 upper bound를 사용해서 range를 제한하거나 걸러낼 수 있다. 예를 들어, 당신은 x와 y 사이의 한 key의 모든 값에 대해 iterate할 수 있다.

+ +

key range에 대한 reference documentation을 위해, IDBKeyRange를 보라.

+
+
+ +

한계점들

+ +

IndexedDB는 client-side storage가 필요한 대부분의 경우를 해결하기 위해 만들어졌다. 하지만 그것은 다음과 같은 몇 가지 경우를 해결하진 못 한다:

+ + + +

덧붙여서, 다음과 같은 조건에서 브라우저가 데이터베이스를 지울 수 있음을 알아두라:

+ + + +

정확한 삭제 시점과 브라우져의 DB 수용능력은 때때로 달라질 수 있습니다만, 브라우져 벤더가 지킬려고 노력하는 가장 기본적인 철학은 데이터를 가능한 최대한 데이터를 지킬려고 노력한다는 것입니다.

+ +

Next steps

+ +

이제 큰 그림은 이해할 수 있게 됐고 아울러 보다 복잡한 사용법을 익힐 준비가 됐네요. 실제로 어떻게 API를 사용하는지 알아보기 위해서, Using IndexedDB를 살펴봅시다.

+ +

함께 보기

+ + + + + + + +
+
+
diff --git a/files/ko/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/ko/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html deleted file mode 100644 index c3d95b2eac..0000000000 --- a/files/ko/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: 기본 개념 -slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -tags: - - Advanced - - IndexedDB -translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB ---- -

{{DefaultAPISidebar("IndexedDB")}}

- -
-

IndexedDB는 사용자의 브라우저 안에 데이터를 영구적으로 저장하게 해주는 방법 중 하나입니다. 그것은 네트워크 가능 여부에 상관없이, 풍부한 쿼리 작성 능력으로 웹 애플리케이션을 만들게 해주고, 이 애플리케이션은 온라인과 오프라인 모두에서 동작할 수 있습니다. IndexedDB는 예를 들면, 도서관의 DVD 목록처럼 대용량 데이터를 저장하는 애플리케이션, 그리고 메일 클라이언트, to-do 리스트, 노트패드처럼 동작에 지속적인 인터넷 연결이 필요하지 않은 애플리케이션에 유용합니다.

-
- -

이 문서에 대하여

- -

이 소개글은 IndexedDB의 필수 개념과 용어에 대해 논의합니다. 큰 그림을 제공하고 핵심 개념들을 설명합니다.

- -

다음과 같은 유용한 정보를 찾을 수 있을 것입니다.

- - - -

IndexedDB 개요

- -

IndexedDB는 "키(key)"로 지정된 객체를 저장하고 검색할 수 있도록 도와줍니다. 데이터베이스에 적용하는 모든 변경은 트렌잭션 안에서 일어납니다. 대부분의 웹 스토리지 솔루션과 마찬가지로, IndexedDB는 동일 출처 정책 (same-origin policy)을 따릅니다. 따라서 당신이 한 도메인의 데이터에 접근하고 있는 동안, 다른 도메인의 데이터에 접근할 수 없습니다.

- -

IndexedDB는 웹 워커를 포함하는 대부분의 문맥(컨텍스트)에 사용될 수 있는 비동기(asynchronous) API입니다. 웹 워커에서 사용하기 위해 동기(synchronous) 버전도 존재했지만, 웹 커뮤니티의 관심부족으로 웹 스펙에서 제거되었습니다.

- -

IndexedDB는 WebSQL 데이터베이스와 경쟁 관계에 있었지만, W3C는 2010 11월 8일에 WebSQL을 폐기(deprecated)하였습니다. IndexedDB와 WebSQL 모두 데이터 저장을 위한 솔루션이지만, 동일한 기능을 제공하지는 않습니다. WebSQL Database는 관계형 데이터베이스 접근 시스템인 반면, IndexedDB는 인덱스 테이블 시스템입니다.

- -

주요 개념들

- -

만약 당신이 다른 DB 시스템을 사용해봤던 경험이 있다면 오히려 잘못된 추측으로 인해 IndexedDB로 작업할 때 힘들어질 수도 있습니다. 그러므로 다음의 중요한 개념들을 잘 정리해 두어야 합니다.

- - - -

정의

- -

이 섹션은 IndexedDB API에서 사용되는 용어들을 정의하고 설명합니다.

- -

데이터베이스

- -
-
데이터베이스
-
일반적으로 하나 혹은 그 이상의 객체 저장소로 구성되는 정보의 레파지토리입니다. 개별 데이터베이스는 다음의 내용을 반드시 가져야 합니다. -
    -
  • 이름(Name). 이것은 하나의 특정 출처 내에서 database를 구별하고 데이터베이스가 존재하는 동안 일정하게 유지됩니다. 이름은 빈 문자열을 포함해서 어떤 문자열 값이라도 될 수 있습니다.
  • -
  • -

    현재 버전. 데이터베이스가 처음 만들어질 때, 따로 지정하지 않으면 버전은 정수 1입니다. 각 데이터베이스는 주어진 순간에 오직 하나의 버전을 가질 수 있습니다.

    -
  • -
-
-
지속성
-
-

파이어폭스에서 indexedDB는 지속성을 유지하기 위해 사용됩니다. 즉, 읽기쓰기 트랜젝션{{domxref("IDBTransaction.oncomplete")}}이 모든 데이터가 디스크로 들어갈 수 있도록 보장될 때에만 실행됩니다.

- -

파이어폭스 40에서, IndexedDB 트랜젝션은 성능을 높이기 위해 지속성 보장을 늦춰왔는데, 이는 IndexedDB를 지원하는 다른 브라우저도 동일한 방식입니다{{Bug("1112702")}}. 이 경우 {{Event("complete")}} 이벤트는 OS가 데이터 쓰기를 하라고 전달한 후, 데이터가 실제로 데이터베이스에 반영되기 전에 잠재적으로 실행됩니다. 이벤트는 이전보다 더 빠르게 전달될지도 모르지만, 만약 OS가 다운되거나 데이터가 데이터베이스에 반영되기 전에 시스템 전원이 부족하면, 전체 트랜젝션은 잃게 될 수도 있는 희박한 위험성이 존재합니다. 그런 치명적인 이벤트는 드물기 때문에, 대부분의 소비자는 더 이상 염려할 필요는 없습니다.

- -
-

Note: 파이어폭스에서 (나중에 다시 계산 할 수 없는 까다로운 데이터를 저장하는 것)과 같은 몇 가지 이유로 지속성을 보장하고 싶다면, complete 이벤트가 전달되기 전에 아직 정식 표준이 아닌 실험적인 readwriteflush 모드를 이용하여 트랜젝션을 데이터베이스에 강제로 반영할 수 있습니다. ({{domxref("IDBDatabase.transaction")}} 참고.) 현재는 실험적으로 적용되어 있고(experimental), about:config에서dom.indexedDB.experimental값이 true 로 설정되어 있을 때만 사용할 수 있습니다.

-
-
-
객체 저장소 ( Object Store )
-
-

데이터베이스에 데이터가 저장되는 매커니즘입니다. 객체 저장소는 키(key)와 값(value)의 쌍으로 된 레코드를 영구적으로 잡습니다. 한 객체 저장소 안의 레코드는 키(key)에 따라 오름차순으로 정렬됩니다.

- -

모든 객체 저장소는 데이터베이스 안에서 고유한 이름을 가져야 합니다. 객체 저장소는 선택적으로 key generatorkey path를 가질 수 있습니다. 만약 객체 저장소가 key path를 가진다면, 그것은 in-line keys를 사용합니다.  아니면, 그것은 out-of-line keys를 사용하는 것입니다.

- -

객체 저장소에 대한 보다 자세한 정보는, IDBObjectStore 또는 IDBObjectStoreSync를 참조하세요.

-
-
version
-
Database가 처음 만들어질 때, version은 정수형 숫자로 1입니다. 각 database는  하나의 version을 집니다; 하나의 데이터베이스가 한번에 여러 version으로 존재할 수 없다. version을 바꾸는 유일한 방법은 현재 버전보다 큰 버전으로 그것을 여는 것입니다. 이렇ㄱ하면 versionchange 트랜잭션을 시작하고 upgradeneeded event를 발생시킵니다. database의 schema를 변경하려면 upgradeneed 이벤트 핸들러내에서 수행해야 합니다.
-
Note: 이 스펙은  most recent specification, which is only implemented in up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
-
database connection
-
 database를 여는 것에 의해 생성되는 operation. 한 주어진 database는 동시에 여러개의 connections를 가질 수 있다.
-
transaction
-
-

특정 database에 대한 data-access와 data-modification operations의 원자적이고 견고한 집합. 그것이 database에서 당신이 data로 상호작용하는 방법이다. 사실, database에서의 어떠한 data의 읽기 또는 변경도 transaction 내에서 일어나야 한다.

- -

하나의 database connection은 한번에 그에 연관된 여러 active transaction을 가질 수 있다, writing transactions이 겹치는 scopes을 갖지 않는 동안. 생성에서 정의되는  transactions의 scope은 그 transaction이 어느 object stores와 상호작용할 수 있는지를 결정하고 그 transaction의 lifetime동안 일정하다. 따라서, 예를 들어, 만약 한 database connection이 flyingMonkey object store를 커버하는 scope의 writing transaction을 이미 가지면, 당신은  unicornCentaur과 unicornPegasus object stores의 scope을 가진 두번째 transaction을 시작할 수 있다. reading transactions로서, 당신은 여러개를 가질 수 있다 — 심지어 겹치는 것들이라도.

- -

Transactions는 short-lived일 것이 기대된다, 그래서 브라우저는 너무 오래걸리는 transaction을 종료할 수 있다, 그 long-running transaction이 lock한 storage resources를 해제하기 위해. 당신은 transaction을 abort할 수 있다 , 이는 그 transaction에서 만들어진 변경들을 roll back한다. 그리고 당신은 심지어 transaction을 abort하기 위해 그것이 시작되거나 활성화되기를 기다릴 필요가 없다.

- -

Transaction의 세가지 모드는: readwrite, readonly, 그리고 versionchange. Object stores와 indexes를 생성하는 유일한 방법은 versionchange transaction을 이용하는 것이다. transaction types를 더 배우기 위해, IndexedDB에 대한 reference article을 보라.

- -

모든 것은 하나의 transaction에서 일어나기 때문에, IndexedDB에서 그것은 매우 중요한 개념이다. transactions에 대해 더 배우기 위해, 특히 그것들이 어떻게 versioning과 관련되는가에 대해, IDBTransaction를 보라, 그는 또한 reference documentation을 가진다. synchronous API에 대한 문서를 위해, IDBTransactionSync를 보라.

-
-
request
-
database에 읽고 쓰기를 행하는 operation. 모든 request는 하나의 읽기 혹은 쓰기 operation을 나타낸다.
-
index
-
-

하나의 index는 다른 object store의 records를 찾기 위한 specialized object store이다, referenced object store라 불리는. index는 그 records의 value part가 referenced object store의 한 record의 key part인 영구적인 key-value storage이다. 하나의 index의 records는 referenced object안에 record가 삽입되고 update되고 삭제될 때마다 자동적으로 생성된다. 하나의 index의 각 record는 그의 referenced object store의 오직 하나의 record를 가리킬 수 있다, 그러나 여러 indexes가 같은 object store를 참조할 수 있다. object store가 변할 때, 그 object store를 참조하는 모든 index는 자동으로 update된다.

- -

다른 방법으로, key를 사용해서 object store에서 records를 찾을 수 있다.

- -

indexes 사용하기에 대해 더 배우기 위해, Using IndexedDB를 보라. index에 대한 reference documentation을 위해, IDBKeyRange를 보라.

-
-
- -

Key and value

- -
-
key
-
-

object store에서 이에 의해 저장된 values가 조직되고 조회되는 하나의 data value. object store는 세 sources 중 하나로부터 key를 이끌어낼 수 있다: key generatorkey path, 또는 명시적으로 지정된 value. key는 그 앞에 있는 것보다 큰 값을 지닌 한 data type의 것이어야 한다. object store의 각 record는 같은 store 내에서 유일한 key를 가져야 한다, 따라서 당신은 주어진 object store에서 같은 key의 여러 records를 가질 수 없다.

- -

하나의 key는 다음의 types 중 하나가 될 수 있다: string, date, float, 그리고 array. arrays에 대해, key는 empty value로부터 infinity의 범위가 될 수 있다. 그리고 당신은 array 내에 array를 포함할 수 있다. string 또는 integer의 key만 사용해야 한다는 요구사항은 없다.

- -

다른 방법으로, 당신은 index를 사용해서 object store에서 records를 찾을 수 있다.

-
-
key generator
-
정렬 sequence로 새 keys를 생성하기 위한 mechanism. 만약 한 object store가 key generator를 가지지 않으면, application은 저장되는 records를 위한 keys를 제공해야 한다. Generators는 stores 간에 공유되지 않는다. 이것은 브라우저 구현 세부사항에 가깝다, 때문에 web 개발에서, 당신은 실제로 key generators를 만들고 접근할 필요가 없다.
-
in-line key
-
저장되는 value의 부분으로서 저장되는 key. key path를 사용함으로써 찾아진다. 하나의 in-line key는 generator를 이용해서 생성될 수 있다. key가 생성된 후에, 그것은 key path를 사용하는 value에 저장될 수 있거나 key로서 사용될 수 있다.
-
out-of-line key
-
저장되는 value와는 따로 저장되는 key.
-
key path
-
object store 또는 index에서 브라우저가 어디로부터 key를 추출해야 하는지 정의한다. 하나의 valid key path는 다음 중 하나를 포함할 수 있다: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods. 그것은 spaces를 포함할 수 없다.
-
value
-
-

각각의 record는 하나의 value를 가진다, 이는 javascript로 표현될 수 있는 어떤 것이라도 포함할 수 있다, boolean, number, string, date, object, array, regexp, undefined, 그리고 null을 포함해서.

- -

object 또는 array가 저장될 때, 그 object 또는 array의  properties 와 values는 적합한 어떤 값이라도 될 수 있다.

- -

Blobs와 files가 저장될 수 있다, cf. specification.

-
-
- -

Range and scope

- -
-
scope
-
한 transaction이 적용되는 object stores와 indexe. read-only transactions의 scope은 겹칠 수 있고 동시에 실행될 수 있다. 한편으로, writing transactions의 scope은 겹칠 수 없다. 당신은 여전히 동시에 같은 scope의 여러 transaction을 실행할 수 있지만 그들은 queue up하고 하나하나 차례로 실행된다.
-
cursor
-
한 key range의 여러 records에 대한 iterating을 위한 mechanism. The cursor는 그것이 iterating하는 것이 어느 index또는 object store인지 가리키는 한 source를 가진다. 그것은 그 range 내의 position을 가지고, record keys의 순서에서 증가 혹은 감소하는 한 방향으로 움직인다. cursors에 대한 reference documentation을 위해, IDBCursor 또는 IDBCursorSync를 보라.
-
key range
-
-

keys를 위해 사용되는 몇몇 data type에 대한 하나의 연속 구간. Records는 keys 또는 하나의 range of keys를 사용하는 object sotres와 indexes로부터 조회될 수 있다. 당신은 lower 그리고 upper bound를 사용해서 range를 제한하거나 걸러낼 수 있다. 예를 들어, 당신은 x와 y 사이의 한 key의 모든 값에 대해 iterate할 수 있다.

- -

key range에 대한 reference documentation을 위해, IDBKeyRange를 보라.

-
-
- -

한계점들

- -

IndexedDB는 client-side storage가 필요한 대부분의 경우를 해결하기 위해 만들어졌다. 하지만 그것은 다음과 같은 몇 가지 경우를 해결하진 못 한다:

- - - -

덧붙여서, 다음과 같은 조건에서 브라우저가 데이터베이스를 지울 수 있음을 알아두라:

- - - -

정확한 삭제 시점과 브라우져의 DB 수용능력은 때때로 달라질 수 있습니다만, 브라우져 벤더가 지킬려고 노력하는 가장 기본적인 철학은 데이터를 가능한 최대한 데이터를 지킬려고 노력한다는 것입니다.

- -

Next steps

- -

이제 큰 그림은 이해할 수 있게 됐고 아울러 보다 복잡한 사용법을 익힐 준비가 됐네요. 실제로 어떻게 API를 사용하는지 알아보기 위해서, Using IndexedDB를 살펴봅시다.

- -

함께 보기

- - - - - - - -
-
-
diff --git a/files/pt-br/_redirects.txt b/files/pt-br/_redirects.txt index 9fa0c02135..6b19fa7931 100644 --- a/files/pt-br/_redirects.txt +++ b/files/pt-br/_redirects.txt @@ -344,7 +344,7 @@ /pt-BR/docs/HTML/Optimizing_Your_Pages_for_Speculative_Parsing /pt-BR/docs/Glossary/speculative_parsing /pt-BR/docs/Hello_World_Rust /pt-BR/docs/orphaned/Hello_World_Rust /pt-BR/docs/IndexedDB /pt-BR/docs/Web/API/IndexedDB_API -/pt-BR/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /pt-BR/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/pt-BR/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /pt-BR/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /pt-BR/docs/IndexedDB/Usando_IndexedDB /pt-BR/docs/Web/API/IndexedDB_API/Using_IndexedDB /pt-BR/docs/Instalando_Rust /pt-BR/docs/orphaned/Instalando_Rust /pt-BR/docs/JSON /pt-BR/docs/Glossary/JSON @@ -577,6 +577,7 @@ /pt-BR/docs/Web/API/HTMLElement/dataset /pt-BR/docs/Web/API/HTMLOrForeignElement/dataset /pt-BR/docs/Web/API/HTMLElement/focus /pt-BR/docs/Web/API/HTMLOrForeignElement/focus /pt-BR/docs/Web/API/History_API/Exemplo /pt-BR/docs/Web/API/History_API/Example +/pt-BR/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /pt-BR/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /pt-BR/docs/Web/API/IndexedDB_API/Usando_IndexedDB /pt-BR/docs/Web/API/IndexedDB_API/Using_IndexedDB /pt-BR/docs/Web/API/Navigator.battery /pt-BR/docs/Web/API/Navigator/battery /pt-BR/docs/Web/API/NavigatorID.platform /pt-BR/docs/Web/API/NavigatorID/platform diff --git a/files/pt-br/_wikihistory.json b/files/pt-br/_wikihistory.json index b724bfc022..357b8546a5 100644 --- a/files/pt-br/_wikihistory.json +++ b/files/pt-br/_wikihistory.json @@ -5758,17 +5758,6 @@ "cirocosta" ] }, - "Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { - "modified": "2020-01-13T04:48:43.968Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "jppaschoal", - "camilaavilarinho", - "guilhermemar", - "IgorGoncalves" - ] - }, "Web/API/IndexedDB_API/Using_IndexedDB": { "modified": "2020-01-13T04:48:43.522Z", "contributors": [ @@ -17147,6 +17136,17 @@ "bermarques" ] }, + "orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { + "modified": "2020-01-13T04:48:43.968Z", + "contributors": [ + "chrisdavidmills", + "wbamberg", + "jppaschoal", + "camilaavilarinho", + "guilhermemar", + "IgorGoncalves" + ] + }, "orphaned/Web/API/Node/Entendendo_o_uso_do_método_AppendChild-javascript": { "modified": "2019-03-23T22:40:45.924Z", "contributors": [ diff --git a/files/pt-br/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/pt-br/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..ae5b41c66d --- /dev/null +++ b/files/pt-br/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,250 @@ +--- +title: Conceitos Básicos sobre IndexedDb +slug: orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +tags: + - Avançado + - IndexedDB + - conceitos +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +original_slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +
+

IndexedDB é uma forma de você armazenar dados no browser do usuário. Permite criar aplicativos da Web com habilidades de consulta ricas, independentemente da disponibilidade da rede, esses aplicativos podem trabalhar on-line e off-line. IndexedDB é útil para aplicativos que armazenam uma grande quantidade de dados (por exemplo, um catálogo de DVDs em uma biblioteca de empréstimos) e aplicativos que não precisam de conectividade persistente à Internet para trabalhar (por exemplo, clientes de e-mail, listas de tarefas e Blocos de notas).

+
+ +

Sobre esse documento

+ +

Essa introdução discute conceitos essenciais e a terminologia do IndexedDB. Ele vai ter dar um visão geral e explicar conceitos chaves.

+ +

Você vai achar útil:

+ + + +

Visão geral do IndexedDB

+ +

IndexedDB permite você armazenar e consultar objetos que são indexados com uma chave. Todas as mudanças na base dados são feitas por transações. Como a maioria soluções de armazenamento web, IndexedDB segue a política de mesma origem. Então enquanto você pode acessar dados armazenados em um domínio, você não pode acessar em diferentes domínios.

+ +

IndexedDB é uma API assíncrona que pode ser usada em diversos contextos, incluindo WebWorkers. Isso permite o uso de uma versão síncrona também, para o uso em web workers, mas isso foi removido da especificação por falta de interesse da comunidade web.

+ +


+ IndexedDB foi pensado para ser uma especificação concorrente ao banco de dados WebSQL, mas o W3C depreciou o WebSQL em 18 de novembro de 2010. Embora IndexedDB e WebSQL sejam soluções para armazenamento, eles não oferecem as mesmas funcionalidades. WebSQL Database é um sistema de acesso a banco de dados relacional, enquanto que IndexedDB é um sistema de tabelas indexadas.

+ +

Principais conceitos

+ +

 Se você já trabalhou com outros tipos de banco de dados, você pode esquecer enquanto trabalha com IndexedDB. E tenha esses importantes conceitos em mente:

+ + + +

 

+ + + +

Definições

+ +

Essa seção define e explica os termos usado na API IndexedDB.

+ +

Base de dados

+ +
+
Base de dados
+
Um repositório de informação, normalmente é composto por um ou mais object stores. cada base de dados deve possuir: +
    +
  • Name. This identifies the database within a specific origin and stays constant throughout its lifetime. The name can be any string value (including an empty string).
  • +
  • +

    Current version. When a database is first created, its version is the integer 1 if not specified otherwise. Each database can have only one version at any given time.

    +
  • +
+
+
durable
+
+

In Firefox, IndexedDB used to be durable, meaning that in a readwrite transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk.

+ +

As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}), which is the same behaviour as other IndexedDB-supporting browsers. In this case the {{Event("complete")}} event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.

+ +
+

Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see {{domxref("IDBDatabase.transaction")}}.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config.

+
+
+
object store
+
+

The mechanism by which data is stored in the database. The object store persistently holds records, which are key-value pairs. Records within an object store are sorted according to the keys in an ascending order.

+ +

Every object store must have a name that is unique within its database. The object store can optionally have a key generator and a key path. If the object store has a key path, it is using in-line keys; otherwise, it is using out-of-line keys.

+ +

For the reference documentation on object store, see IDBObjectStore or IDBObjectStoreSync.

+
+
version
+
When a database is first created, its version is the integer 1. Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is by opening it with a greater version than the current one. This will start a versionchange transaction and fire an upgradeneeded event. The only place where the schema of the database can be updated is inside the handler of that event.
+
Note: This definition describes the most recent specification, which is only implemented in up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
+
database connection
+
An operation created by opening a database. A given database can have multiple connections at the same time.
+
transaction
+
+

An atomic set of data-access and data-modification operations on a particular database. It is how you interact with the data in a database. In fact, any reading or changing of data in the database must happen in a transaction.

+ +

A database connection can have several active transaction associated with it at a time, so long as the writing transactions do not have overlapping scopes. The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the flyingMonkey object store, you can start a second transaction with a scope of the unicornCentaur and unicornPegasus object stores. As for reading transactions, you can have several of them — even overlapping ones.

+ +

Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.

+ +

The three modes of transactions are: readwrite, readonly, and versionchange. The only way to create and delete object stores and indexes is by using a versionchange transaction. To learn more about transaction types, see the reference article for IndexedDB.

+ +

Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see IDBTransaction, which also has reference documentation. For the documentation on the synchronous API, see IDBTransactionSync.

+
+
request
+
The operation by which reading and writing on a database is done. Every request represents one read or write operation.
+
index
+
+

An index is a specialized object store for looking up records in another object store, called the referenced object store. The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. Each record in an index can point to only one record in its referenced object store, but several indexes can reference the same object store. When the object store changes, all indexes that refer to the object store are automatically updated.

+ +

Alternatively, you can also look up records in an object store using the key.

+ +

To learn more on using indexes, see Using IndexedDB. For the reference documentation on index, see IDBKeyRange.

+
+
+ +

Chave e valor

+ +
+
key
+
+

A data value by which stored values are organized and retrieved in the object store. The object store can derive the key from one of three sources: a key generator, a key path, or an explicitly specified value. The key must be of a data type that has a number that is greater than the one before it. Each record in an object store must have a key that is unique within the same store, so you cannot have multiple records with the same key in a given object store.

+ +

A key can be one of the following types: string, date, float, a binary blob, and array. For arrays, the key can range from an empty value to infinity. And you can include an array within an array.

+ +

Alternatively, you can also look up records in an object store using the index.

+
+
key generator
+
A mechanism for producing new keys in an ordered sequence. If an object store does not have a key generator, then the application must provide keys for records being stored. Generators are not shared between stores. This is more a browser implementation detail, because in web development, you don't really create or access key generators.
+
in-line key
+
A key that is stored as part of the stored value. It is found using a key path. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
+
out-of-line key
+
A key that is stored separately from the value being stored.
+
key path
+
Defines where the browser should extract the key from in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods or an array containing any of those. It cannot include spaces.
+
value
+
+

Each record has a value, which could include anything that can be expressed in JavaScript, including boolean, number, string, date, object, array, regexp, undefined, and null.

+ +

When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.

+ +

Blobs and files can be stored, cf. specification.

+
+
+ +

Intervalo e escopo

+ +
+
scope
+
The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
+
cursor
+
A mechanism for iterating over multiple records with a key range. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see IDBCursor or IDBCursorSync.
+
key range
+
+

A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.

+ +

For the reference documentation on key range, see IDBKeyRange.

+
+
+ +

Limitações

+ +

IndexedDB is designed to cover most cases that need client-side storage. However, it is not designed for a few cases like the following:

+ + + +

In addition, be aware that browsers can wipe out the database, such as in the following conditions:

+ + + +

The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible.

+ +

Próximos passos

+ +

With these big concepts under our belts, we can get to more concrete stuff. For a tutorial on how to use the API, see Using IndexedDB.

+ +

See also

+ +

Especificação

+ + + +

Referência

+ + + +

Tutoriais

+ + + +

Artigo relacionado

+ + diff --git a/files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html deleted file mode 100644 index 1ec04d3838..0000000000 --- a/files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Conceitos Básicos sobre IndexedDb -slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -tags: - - Avançado - - IndexedDB - - conceitos -translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB ---- -

{{DefaultAPISidebar("IndexedDB")}}

- -
-

IndexedDB é uma forma de você armazenar dados no browser do usuário. Permite criar aplicativos da Web com habilidades de consulta ricas, independentemente da disponibilidade da rede, esses aplicativos podem trabalhar on-line e off-line. IndexedDB é útil para aplicativos que armazenam uma grande quantidade de dados (por exemplo, um catálogo de DVDs em uma biblioteca de empréstimos) e aplicativos que não precisam de conectividade persistente à Internet para trabalhar (por exemplo, clientes de e-mail, listas de tarefas e Blocos de notas).

-
- -

Sobre esse documento

- -

Essa introdução discute conceitos essenciais e a terminologia do IndexedDB. Ele vai ter dar um visão geral e explicar conceitos chaves.

- -

Você vai achar útil:

- - - -

Visão geral do IndexedDB

- -

IndexedDB permite você armazenar e consultar objetos que são indexados com uma chave. Todas as mudanças na base dados são feitas por transações. Como a maioria soluções de armazenamento web, IndexedDB segue a política de mesma origem. Então enquanto você pode acessar dados armazenados em um domínio, você não pode acessar em diferentes domínios.

- -

IndexedDB é uma API assíncrona que pode ser usada em diversos contextos, incluindo WebWorkers. Isso permite o uso de uma versão síncrona também, para o uso em web workers, mas isso foi removido da especificação por falta de interesse da comunidade web.

- -


- IndexedDB foi pensado para ser uma especificação concorrente ao banco de dados WebSQL, mas o W3C depreciou o WebSQL em 18 de novembro de 2010. Embora IndexedDB e WebSQL sejam soluções para armazenamento, eles não oferecem as mesmas funcionalidades. WebSQL Database é um sistema de acesso a banco de dados relacional, enquanto que IndexedDB é um sistema de tabelas indexadas.

- -

Principais conceitos

- -

 Se você já trabalhou com outros tipos de banco de dados, você pode esquecer enquanto trabalha com IndexedDB. E tenha esses importantes conceitos em mente:

- - - -

 

- - - -

Definições

- -

Essa seção define e explica os termos usado na API IndexedDB.

- -

Base de dados

- -
-
Base de dados
-
Um repositório de informação, normalmente é composto por um ou mais object stores. cada base de dados deve possuir: -
    -
  • Name. This identifies the database within a specific origin and stays constant throughout its lifetime. The name can be any string value (including an empty string).
  • -
  • -

    Current version. When a database is first created, its version is the integer 1 if not specified otherwise. Each database can have only one version at any given time.

    -
  • -
-
-
durable
-
-

In Firefox, IndexedDB used to be durable, meaning that in a readwrite transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk.

- -

As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}), which is the same behaviour as other IndexedDB-supporting browsers. In this case the {{Event("complete")}} event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.

- -
-

Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see {{domxref("IDBDatabase.transaction")}}.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config.

-
-
-
object store
-
-

The mechanism by which data is stored in the database. The object store persistently holds records, which are key-value pairs. Records within an object store are sorted according to the keys in an ascending order.

- -

Every object store must have a name that is unique within its database. The object store can optionally have a key generator and a key path. If the object store has a key path, it is using in-line keys; otherwise, it is using out-of-line keys.

- -

For the reference documentation on object store, see IDBObjectStore or IDBObjectStoreSync.

-
-
version
-
When a database is first created, its version is the integer 1. Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is by opening it with a greater version than the current one. This will start a versionchange transaction and fire an upgradeneeded event. The only place where the schema of the database can be updated is inside the handler of that event.
-
Note: This definition describes the most recent specification, which is only implemented in up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
-
database connection
-
An operation created by opening a database. A given database can have multiple connections at the same time.
-
transaction
-
-

An atomic set of data-access and data-modification operations on a particular database. It is how you interact with the data in a database. In fact, any reading or changing of data in the database must happen in a transaction.

- -

A database connection can have several active transaction associated with it at a time, so long as the writing transactions do not have overlapping scopes. The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the flyingMonkey object store, you can start a second transaction with a scope of the unicornCentaur and unicornPegasus object stores. As for reading transactions, you can have several of them — even overlapping ones.

- -

Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.

- -

The three modes of transactions are: readwrite, readonly, and versionchange. The only way to create and delete object stores and indexes is by using a versionchange transaction. To learn more about transaction types, see the reference article for IndexedDB.

- -

Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see IDBTransaction, which also has reference documentation. For the documentation on the synchronous API, see IDBTransactionSync.

-
-
request
-
The operation by which reading and writing on a database is done. Every request represents one read or write operation.
-
index
-
-

An index is a specialized object store for looking up records in another object store, called the referenced object store. The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. Each record in an index can point to only one record in its referenced object store, but several indexes can reference the same object store. When the object store changes, all indexes that refer to the object store are automatically updated.

- -

Alternatively, you can also look up records in an object store using the key.

- -

To learn more on using indexes, see Using IndexedDB. For the reference documentation on index, see IDBKeyRange.

-
-
- -

Chave e valor

- -
-
key
-
-

A data value by which stored values are organized and retrieved in the object store. The object store can derive the key from one of three sources: a key generator, a key path, or an explicitly specified value. The key must be of a data type that has a number that is greater than the one before it. Each record in an object store must have a key that is unique within the same store, so you cannot have multiple records with the same key in a given object store.

- -

A key can be one of the following types: string, date, float, a binary blob, and array. For arrays, the key can range from an empty value to infinity. And you can include an array within an array.

- -

Alternatively, you can also look up records in an object store using the index.

-
-
key generator
-
A mechanism for producing new keys in an ordered sequence. If an object store does not have a key generator, then the application must provide keys for records being stored. Generators are not shared between stores. This is more a browser implementation detail, because in web development, you don't really create or access key generators.
-
in-line key
-
A key that is stored as part of the stored value. It is found using a key path. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
-
out-of-line key
-
A key that is stored separately from the value being stored.
-
key path
-
Defines where the browser should extract the key from in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods or an array containing any of those. It cannot include spaces.
-
value
-
-

Each record has a value, which could include anything that can be expressed in JavaScript, including boolean, number, string, date, object, array, regexp, undefined, and null.

- -

When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.

- -

Blobs and files can be stored, cf. specification.

-
-
- -

Intervalo e escopo

- -
-
scope
-
The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
-
cursor
-
A mechanism for iterating over multiple records with a key range. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see IDBCursor or IDBCursorSync.
-
key range
-
-

A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.

- -

For the reference documentation on key range, see IDBKeyRange.

-
-
- -

Limitações

- -

IndexedDB is designed to cover most cases that need client-side storage. However, it is not designed for a few cases like the following:

- - - -

In addition, be aware that browsers can wipe out the database, such as in the following conditions:

- - - -

The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible.

- -

Próximos passos

- -

With these big concepts under our belts, we can get to more concrete stuff. For a tutorial on how to use the API, see Using IndexedDB.

- -

See also

- -

Especificação

- - - -

Referência

- - - -

Tutoriais

- - - -

Artigo relacionado

- - diff --git a/files/ru/_redirects.txt b/files/ru/_redirects.txt index 481eba78db..045b03513d 100644 --- a/files/ru/_redirects.txt +++ b/files/ru/_redirects.txt @@ -112,7 +112,7 @@ /ru/docs/HTML/HTML5/Введение_в_HTML5 /ru/docs/orphaned/Web/Guide/HTML/HTML5/Introduction_to_HTML5 /ru/docs/HTML/Optimizing_Your_Pages_for_Speculative_Parsing /ru/docs/Glossary/speculative_parsing /ru/docs/IndexedDB /ru/docs/Web/API/IndexedDB_API -/ru/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /ru/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/ru/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /ru/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /ru/docs/IndexedDB/Using_IndexedDB /ru/docs/Web/API/IndexedDB_API/Using_IndexedDB /ru/docs/JavaScript /ru/docs/Web/JavaScript /ru/docs/JavaScript/A_re-introduction_to_JavaScript /ru/docs/Web/JavaScript/A_re-introduction_to_JavaScript @@ -427,6 +427,7 @@ /ru/docs/Web/API/HTMLHyperlinkElementUtils/toString /ru/docs/Web/API/HTMLAnchorElement/toString /ru/docs/Web/API/HTMLHyperlinkElementUtils/username /ru/docs/Web/API/HTMLAnchorElement/username /ru/docs/Web/API/HTMLImageElement.Image /ru/docs/Web/API/HTMLImageElement/Image +/ru/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /ru/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /ru/docs/Web/API/MediaTrackConstraints/Эхоподавление /ru/docs/Web/API/MediaTrackConstraints/echoCancellation /ru/docs/Web/API/NavigatorGeolocation /ru/docs/conflicting/Web/API/Geolocation /ru/docs/Web/API/NetworkInformation/connection /ru/docs/Web/API/Navigator/connection @@ -726,6 +727,7 @@ /ru/docs/Web/JavaScript/New_in_JavaScript/Новое_в_JavaScript_1.6 /ru/docs/Web/JavaScript/New_in_JavaScript/1.6 /ru/docs/Web/JavaScript/Reference/Classes/Class_fields /ru/docs/Web/JavaScript/Reference/Classes/Public_class_fields /ru/docs/Web/JavaScript/Reference/Classes/Приватные_поля_класса /ru/docs/Web/JavaScript/Reference/Classes/Private_class_fields +/ru/docs/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /ru/docs/orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /ru/docs/Web/JavaScript/Reference/Errors/Переменные_скрывают_аргумент /ru/docs/Web/JavaScript/Reference/Errors/Var_hides_argument /ru/docs/Web/JavaScript/Reference/Functions/Определиние_методов /ru/docs/Web/JavaScript/Reference/Functions/Method_definitions /ru/docs/Web/JavaScript/Reference/Global_Objects/Array/contains /ru/docs/Web/JavaScript/Reference/Global_Objects/Array/includes diff --git a/files/ru/_wikihistory.json b/files/ru/_wikihistory.json index 4e3e9d7e5b..8282d967ba 100644 --- a/files/ru/_wikihistory.json +++ b/files/ru/_wikihistory.json @@ -9297,15 +9297,6 @@ "madarche" ] }, - "Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { - "modified": "2020-08-02T03:41:34.455Z", - "contributors": [ - "ijetsoft", - "S-le", - "chrisdavidmills", - "curdwithraisins" - ] - }, "Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria": { "modified": "2020-12-13T06:01:46.717Z", "contributors": [ @@ -18651,13 +18642,6 @@ "thepocp" ] }, - "Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { - "modified": "2020-03-12T19:48:42.436Z", - "contributors": [ - "fuggy", - "MakarovDs777" - ] - }, "Web/JavaScript/Reference/Errors/Undeclared_var": { "modified": "2020-03-12T19:47:38.776Z", "contributors": [ @@ -25481,6 +25465,15 @@ "teoli" ] }, + "orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { + "modified": "2020-08-02T03:41:34.455Z", + "contributors": [ + "ijetsoft", + "S-le", + "chrisdavidmills", + "curdwithraisins" + ] + }, "orphaned/Web/API/Notation": { "modified": "2020-10-15T22:17:39.773Z", "contributors": [ @@ -25682,6 +25675,13 @@ "danielgn96" ] }, + "orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { + "modified": "2020-03-12T19:48:42.436Z", + "contributors": [ + "fuggy", + "MakarovDs777" + ] + }, "orphaned/Web/JavaScript/Reference/Global_Objects/Array/prototype": { "modified": "2020-10-15T21:23:46.631Z", "contributors": [ diff --git a/files/ru/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/ru/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..0e9312398c --- /dev/null +++ b/files/ru/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,214 @@ +--- +title: Basic concepts +slug: orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +original_slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +
+

IndexedDB обеспечивает возможность постоянного хранения данных посредством браузера пользователя. Поскольку это наделяет создаваемые web-приложения с расширенными возможностями независимостью от доступа к сети, такие приложения получают возможность работы как online, так и offline. IndexedDB полезна для приложений, хранящих большое количество данных (например, каталог DVD библиотеки проката) и не нуждающихся в постоянном подключении к Интернету (например, почтовые клиенты, перечни запланированного to-do и заметки на память).

+
+ +

Об этом документе

+ +

В этом введении рассматриваются основные концепции и термины в IndexedDB. Оно содержит общую картину и объясняет ключевые понятия.

+ +

Оно может стать полезным для:

+ + + +

Обзор IndexedDB

+ +

IndexedDB позволяет сохранять и извлекать объекты, проиндексированные с помощью "ключа". Все манипуляции над базой данных происходят при помощи транзакций. Как и большинство решений для web-хранилищ, IndexedDB следует same-origin policy. Поэтому, если получить доступ к сохранённым данным в пределах домена можно, то вне его - нет.

+ +

IndexedDB - асинхронное API, которое может быть использовано в большинстве контекстов, включая Web Workers. Раньше оно включало синхронную версию, для использования в web workers, но это было удалено из спецификации в связи с недостатком интереса внутри web-сообщества.

+ +

Существует так же конкурирующая с IndexedDB спецификация, WebSQL Database, но W3C исключила её 18 ноября 2010. Хотя IndexedDB и WebSQL оба являются решением для хранилищ, они предоставляют различный функционал. WebSQL Database - реляционная система доступа к базам данных, когда IndexedDB - система индексированной таблицы.

+ +

Big concepts

+ +

Если у вас есть опыт работы с другими типами баз данных, то вы можете быть сбиты с толку в процессе работы с IndexedDB. Поэтому имейте в виду следующие важные понятия:

+ + + +

Definitions

+ +

This section defines and explains terms used in the IndexedDB API.

+ +

Database

+ +
+
database
+
A repository of information, typically comprising one or more object stores. Each database must have the following: +
    +
  • Name. This identifies the database within a specific origin and stays constant throughout its lifetime. The name can be any string value (including an empty string).
  • +
  • +

    Current version. When a database is first created, its version is the integer 1 if not specified otherwise. Each database can have only one version at any given time.

    +
  • +
+
+
durable
+
+

In Firefox, IndexedDB used to be durable, meaning that in a readwrite transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk.

+ +

As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}), which is the same behaviour as other IndexedDB-supporting browsers. In this case the {{Event("complete")}} event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.

+ +
+

Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see {{domxref("IDBDatabase.transaction")}}.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config.

+
+
+
object store
+
+

The mechanism by which data is stored in the database. The object store persistently holds records, which are key-value pairs. Records within an object store are sorted according to the keys in an ascending order.

+ +

Every object store must have a name that is unique within its database. The object store can optionally have a key generator and a key path. If the object store has a key path, it is using in-line keys; otherwise, it is using out-of-line keys.

+ +

For the reference documentation on object store, see {{domxref("IDBObjectStore")}}.

+
+
version
+
When a database is first created, its version is the integer 1. Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is by opening it with a greater version than the current one. This will start a versionchange transaction and fire an upgradeneeded event. The only place where the schema of the database can be updated is inside the handler of that event.
+
Note: This definition describes the most recent specification, which is only implemented in up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
+
database connection
+
An operation created by opening a database. A given database can have multiple connections at the same time.
+
transaction
+
+

An atomic set of data-access and data-modification operations on a particular database. It is how you interact with the data in a database. In fact, any reading or changing of data in the database must happen in a transaction.

+ +

A database connection can have several active transactions associated with it at a time, so long as the writing transactions do not have overlapping scopes. The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the flyingMonkey object store, you can start a second transaction with a scope of the unicornCentaur and unicornPegasus object stores. As for reading transactions, you can have several of them — even overlapping ones.

+ +

Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.

+ +

The three modes of transactions are: readwrite, readonly, and versionchange. The only way to create and delete object stores and indexes is by using a versionchange transaction. To learn more about transaction types, see the reference article for IndexedDB.

+ +

Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see {{domxref("IDBTransaction")}}, which also has reference documentation.

+
+
request
+
The operation by which reading and writing on a database is done. Every request represents one read or write operation.
+
index
+
+

An index is a specialized object store for looking up records in another object store, called the referenced object store. The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. Each record in an index can point to only one record in its referenced object store, but several indexes can reference the same object store. When the object store changes, all indexes that refer to the object store are automatically updated.

+ +

Alternatively, you can also look up records in an object store using the key.

+ +

To learn more on using indexes, see Using IndexedDB. For the reference documentation on index, see IDBKeyRange.

+
+
+ +

Key and value

+ +
+
key
+
+

A data value by which stored values are organized and retrieved in the object store. The object store can derive the key from one of three sources: a key generator, a key path, or an explicitly specified value. The key must be of a data type that has a number that is greater than the one before it. Each record in an object store must have a key that is unique within the same store, so you cannot have multiple records with the same key in a given object store.

+ +

A key can be one of the following types: string, date, float, a binary blob, and array. For arrays, the key can range from an empty value to infinity. And you can include an array within an array.

+ +

Alternatively, you can also look up records in an object store using the index.

+
+
key generator
+
A mechanism for producing new keys in an ordered sequence. If an object store does not have a key generator, then the application must provide keys for records being stored. Generators are not shared between stores. This is more a browser implementation detail, because in web development, you don't really create or access key generators.
+
in-line key
+
A key that is stored as part of the stored value. It is found using a key path. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
+
out-of-line key
+
A key that is stored separately from the value being stored.
+
key path
+
Defines where the browser should extract the key from in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods or an array containing any of those. It cannot include spaces.
+
value
+
+

Each record has a value, which could include anything that can be expressed in JavaScript, including boolean, number, string, date, object, array, regexp, undefined, and null.

+ +

When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.

+ +

Blobs and files can be stored, cf. specification.

+
+
+ +

Range and scope

+ +
+
scope
+
The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
+
cursor
+
A mechanism for iterating over multiple records with a key range. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see {{domxref("IDBCursor")}}.
+
key range
+
+

A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.

+ +

For the reference documentation on key range, see {{domxref("IDBKeyRange")}}.

+
+
+ +

Limitations

+ +

IndexedDB is designed to cover most cases that need client-side storage. However, it is not designed for a few cases like the following:

+ + + +

In addition, be aware that browsers can wipe out the database, such as in the following conditions:

+ + + +

The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible.

+ +

Next steps

+ +

With these big concepts under our belts, we can get to more concrete stuff. For a tutorial on how to use the API, see Using IndexedDB.

+ +

See also

+ + diff --git a/files/ru/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/ru/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html new file mode 100644 index 0000000000..ab6bcf3748 --- /dev/null +++ b/files/ru/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html @@ -0,0 +1,79 @@ +--- +title: 'TypeError: invalid arguments' +slug: orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +tags: + - Error + - Errors + - JavaScript + - TypeError + - Ошибки +translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +original_slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +--- +
{{jsSidebar("Errors")}}
+ +

Сообщение

+ +
TypeError: invalid arguments (Firefox)
+ +

Тип ошибки

+ +

{{jsxref("TypeError")}}

+ +

Что не так?

+ +

Конструкторы типизированных массивов требуют либо

+ + + +

чтобы создать новый типизированный массив. Другие аргументы конструктора не создают допустимый типизированный массив.

+ +

Примеры

+ +

Типизированные массивы, например {{jsxref("Uint8Array")}}, не могут быть построены из строки. На самом деле строки вообще не могут быть в типизированных массивах.

+ +
var ta = new Uint8Array("nope");
+// TypeError: invalid arguments
+
+ +

Различные способы создания допустимого {{jsxref("Uint8Array")}}:

+ +
 // From a length
+var uint8 = new Uint8Array(2);
+uint8[0] = 42;
+console.log(uint8[0]); // 42
+console.log(uint8.length); // 2
+console.log(uint8.BYTES_PER_ELEMENT); // 1
+
+// From an array
+var arr = new Uint8Array([21,31]);
+console.log(arr[1]); // 31
+
+// From another TypedArray
+var x = new Uint8Array([21, 31]);
+var y = new Uint8Array(x);
+console.log(y[0]); // 21
+
+// From an ArrayBuffer
+var buffer = new ArrayBuffer(8);
+var z = new Uint8Array(buffer, 1, 4);
+
+// From an iterable
+var iterable = function*(){ yield* [1,2,3]; }();
+var uint8 = new Uint8Array(iterable);
+// Uint8Array[1, 2, 3]
+
+ +

Смотрите также

+ + diff --git a/files/ru/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/ru/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html deleted file mode 100644 index 567f0a3d79..0000000000 --- a/files/ru/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Basic concepts -slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB ---- -

{{DefaultAPISidebar("IndexedDB")}}

- -
-

IndexedDB обеспечивает возможность постоянного хранения данных посредством браузера пользователя. Поскольку это наделяет создаваемые web-приложения с расширенными возможностями независимостью от доступа к сети, такие приложения получают возможность работы как online, так и offline. IndexedDB полезна для приложений, хранящих большое количество данных (например, каталог DVD библиотеки проката) и не нуждающихся в постоянном подключении к Интернету (например, почтовые клиенты, перечни запланированного to-do и заметки на память).

-
- -

Об этом документе

- -

В этом введении рассматриваются основные концепции и термины в IndexedDB. Оно содержит общую картину и объясняет ключевые понятия.

- -

Оно может стать полезным для:

- - - -

Обзор IndexedDB

- -

IndexedDB позволяет сохранять и извлекать объекты, проиндексированные с помощью "ключа". Все манипуляции над базой данных происходят при помощи транзакций. Как и большинство решений для web-хранилищ, IndexedDB следует same-origin policy. Поэтому, если получить доступ к сохранённым данным в пределах домена можно, то вне его - нет.

- -

IndexedDB - асинхронное API, которое может быть использовано в большинстве контекстов, включая Web Workers. Раньше оно включало синхронную версию, для использования в web workers, но это было удалено из спецификации в связи с недостатком интереса внутри web-сообщества.

- -

Существует так же конкурирующая с IndexedDB спецификация, WebSQL Database, но W3C исключила её 18 ноября 2010. Хотя IndexedDB и WebSQL оба являются решением для хранилищ, они предоставляют различный функционал. WebSQL Database - реляционная система доступа к базам данных, когда IndexedDB - система индексированной таблицы.

- -

Big concepts

- -

Если у вас есть опыт работы с другими типами баз данных, то вы можете быть сбиты с толку в процессе работы с IndexedDB. Поэтому имейте в виду следующие важные понятия:

- - - -

Definitions

- -

This section defines and explains terms used in the IndexedDB API.

- -

Database

- -
-
database
-
A repository of information, typically comprising one or more object stores. Each database must have the following: -
    -
  • Name. This identifies the database within a specific origin and stays constant throughout its lifetime. The name can be any string value (including an empty string).
  • -
  • -

    Current version. When a database is first created, its version is the integer 1 if not specified otherwise. Each database can have only one version at any given time.

    -
  • -
-
-
durable
-
-

In Firefox, IndexedDB used to be durable, meaning that in a readwrite transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk.

- -

As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}), which is the same behaviour as other IndexedDB-supporting browsers. In this case the {{Event("complete")}} event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.

- -
-

Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see {{domxref("IDBDatabase.transaction")}}.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config.

-
-
-
object store
-
-

The mechanism by which data is stored in the database. The object store persistently holds records, which are key-value pairs. Records within an object store are sorted according to the keys in an ascending order.

- -

Every object store must have a name that is unique within its database. The object store can optionally have a key generator and a key path. If the object store has a key path, it is using in-line keys; otherwise, it is using out-of-line keys.

- -

For the reference documentation on object store, see {{domxref("IDBObjectStore")}}.

-
-
version
-
When a database is first created, its version is the integer 1. Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is by opening it with a greater version than the current one. This will start a versionchange transaction and fire an upgradeneeded event. The only place where the schema of the database can be updated is inside the handler of that event.
-
Note: This definition describes the most recent specification, which is only implemented in up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
-
database connection
-
An operation created by opening a database. A given database can have multiple connections at the same time.
-
transaction
-
-

An atomic set of data-access and data-modification operations on a particular database. It is how you interact with the data in a database. In fact, any reading or changing of data in the database must happen in a transaction.

- -

A database connection can have several active transactions associated with it at a time, so long as the writing transactions do not have overlapping scopes. The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the flyingMonkey object store, you can start a second transaction with a scope of the unicornCentaur and unicornPegasus object stores. As for reading transactions, you can have several of them — even overlapping ones.

- -

Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.

- -

The three modes of transactions are: readwrite, readonly, and versionchange. The only way to create and delete object stores and indexes is by using a versionchange transaction. To learn more about transaction types, see the reference article for IndexedDB.

- -

Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see {{domxref("IDBTransaction")}}, which also has reference documentation.

-
-
request
-
The operation by which reading and writing on a database is done. Every request represents one read or write operation.
-
index
-
-

An index is a specialized object store for looking up records in another object store, called the referenced object store. The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. Each record in an index can point to only one record in its referenced object store, but several indexes can reference the same object store. When the object store changes, all indexes that refer to the object store are automatically updated.

- -

Alternatively, you can also look up records in an object store using the key.

- -

To learn more on using indexes, see Using IndexedDB. For the reference documentation on index, see IDBKeyRange.

-
-
- -

Key and value

- -
-
key
-
-

A data value by which stored values are organized and retrieved in the object store. The object store can derive the key from one of three sources: a key generator, a key path, or an explicitly specified value. The key must be of a data type that has a number that is greater than the one before it. Each record in an object store must have a key that is unique within the same store, so you cannot have multiple records with the same key in a given object store.

- -

A key can be one of the following types: string, date, float, a binary blob, and array. For arrays, the key can range from an empty value to infinity. And you can include an array within an array.

- -

Alternatively, you can also look up records in an object store using the index.

-
-
key generator
-
A mechanism for producing new keys in an ordered sequence. If an object store does not have a key generator, then the application must provide keys for records being stored. Generators are not shared between stores. This is more a browser implementation detail, because in web development, you don't really create or access key generators.
-
in-line key
-
A key that is stored as part of the stored value. It is found using a key path. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
-
out-of-line key
-
A key that is stored separately from the value being stored.
-
key path
-
Defines where the browser should extract the key from in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods or an array containing any of those. It cannot include spaces.
-
value
-
-

Each record has a value, which could include anything that can be expressed in JavaScript, including boolean, number, string, date, object, array, regexp, undefined, and null.

- -

When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.

- -

Blobs and files can be stored, cf. specification.

-
-
- -

Range and scope

- -
-
scope
-
The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
-
cursor
-
A mechanism for iterating over multiple records with a key range. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see {{domxref("IDBCursor")}}.
-
key range
-
-

A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.

- -

For the reference documentation on key range, see {{domxref("IDBKeyRange")}}.

-
-
- -

Limitations

- -

IndexedDB is designed to cover most cases that need client-side storage. However, it is not designed for a few cases like the following:

- - - -

In addition, be aware that browsers can wipe out the database, such as in the following conditions:

- - - -

The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible.

- -

Next steps

- -

With these big concepts under our belts, we can get to more concrete stuff. For a tutorial on how to use the API, see Using IndexedDB.

- -

See also

- - diff --git a/files/ru/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/ru/web/javascript/reference/errors/typed_array_invalid_arguments/index.html deleted file mode 100644 index 076743b50c..0000000000 --- a/files/ru/web/javascript/reference/errors/typed_array_invalid_arguments/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: 'TypeError: invalid arguments' -slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments -tags: - - Error - - Errors - - JavaScript - - TypeError - - Ошибки -translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments ---- -
{{jsSidebar("Errors")}}
- -

Сообщение

- -
TypeError: invalid arguments (Firefox)
- -

Тип ошибки

- -

{{jsxref("TypeError")}}

- -

Что не так?

- -

Конструкторы типизированных массивов требуют либо

- - - -

чтобы создать новый типизированный массив. Другие аргументы конструктора не создают допустимый типизированный массив.

- -

Примеры

- -

Типизированные массивы, например {{jsxref("Uint8Array")}}, не могут быть построены из строки. На самом деле строки вообще не могут быть в типизированных массивах.

- -
var ta = new Uint8Array("nope");
-// TypeError: invalid arguments
-
- -

Различные способы создания допустимого {{jsxref("Uint8Array")}}:

- -
 // From a length
-var uint8 = new Uint8Array(2);
-uint8[0] = 42;
-console.log(uint8[0]); // 42
-console.log(uint8.length); // 2
-console.log(uint8.BYTES_PER_ELEMENT); // 1
-
-// From an array
-var arr = new Uint8Array([21,31]);
-console.log(arr[1]); // 31
-
-// From another TypedArray
-var x = new Uint8Array([21, 31]);
-var y = new Uint8Array(x);
-console.log(y[0]); // 21
-
-// From an ArrayBuffer
-var buffer = new ArrayBuffer(8);
-var z = new Uint8Array(buffer, 1, 4);
-
-// From an iterable
-var iterable = function*(){ yield* [1,2,3]; }();
-var uint8 = new Uint8Array(iterable);
-// Uint8Array[1, 2, 3]
-
- -

Смотрите также

- - diff --git a/files/zh-cn/_redirects.txt b/files/zh-cn/_redirects.txt index 62de81aff3..84abaed1cf 100644 --- a/files/zh-cn/_redirects.txt +++ b/files/zh-cn/_redirects.txt @@ -706,7 +706,7 @@ /zh-CN/docs/HTTP /zh-CN/docs/Web/HTTP /zh-CN/docs/HTTP/HTTP_response_codes /zh-CN/docs/conflicting/Web/HTTP/Status /zh-CN/docs/IndexedDB /zh-CN/docs/Web/API/IndexedDB_API -/zh-CN/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /zh-CN/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/zh-CN/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /zh-CN/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /zh-CN/docs/IndexedDB/IDBObjectStore /zh-CN/docs/Web/API/IDBObjectStore /zh-CN/docs/IndexedDB/Using_IndexedDB /zh-CN/docs/Web/API/IndexedDB_API/Using_IndexedDB /zh-CN/docs/Introducing_the_Audio_API_Extension /zh-CN/docs/Introducing_Audio_API_Extension @@ -1645,6 +1645,7 @@ /zh-CN/docs/Web/API/IDBCursor.direction /zh-CN/docs/Web/API/IDBCursor/direction /zh-CN/docs/Web/API/IDBFactory.open /zh-CN/docs/Web/API/IDBFactory/open /zh-CN/docs/Web/API/IDBObjectStore.openCursor /zh-CN/docs/Web/API/IDBObjectStore/openCursor +/zh-CN/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /zh-CN/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /zh-CN/docs/Web/API/IndexedDB_API/IDBObjectStore /zh-CN/docs/Web/API/IDBObjectStore /zh-CN/docs/Web/API/Intersection_Observer_API/点观察者API的时序元素可见性 /zh-CN/docs/Web/API/Intersection_Observer_API/Timing_element_visibility /zh-CN/docs/Web/API/Location.replace /zh-CN/docs/Web/API/Location/replace @@ -2472,6 +2473,7 @@ /zh-CN/docs/Web/JavaScript/Reference/Date/setTime /zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime /zh-CN/docs/Web/JavaScript/Reference/Date/toJSON /zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON /zh-CN/docs/Web/JavaScript/Reference/Date/valueOf /zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf +/zh-CN/docs/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /zh-CN/docs/orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments /zh-CN/docs/Web/JavaScript/Reference/Errors/不能添加属性 /zh-CN/docs/Web/JavaScript/Reference/Errors/Cant_assign_to_property /zh-CN/docs/Web/JavaScript/Reference/Function /zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function /zh-CN/docs/Web/JavaScript/Reference/Function/apply /zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply diff --git a/files/zh-cn/_wikihistory.json b/files/zh-cn/_wikihistory.json index 5eeb393762..74fdf0490c 100644 --- a/files/zh-cn/_wikihistory.json +++ b/files/zh-cn/_wikihistory.json @@ -16580,28 +16580,6 @@ "princetoad@gmail.com" ] }, - "Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { - "modified": "2019-09-29T21:07:32.199Z", - "contributors": [ - "Nonym", - "Zaynex", - "nztraveler", - "hooozen", - "SphinxKnight", - "gaoryrt", - "WenWu92", - "Yongest", - "RyanBeauclerc", - "em2046", - "ywwzwb", - "ziyunfei", - "mountainmoon", - "Fify", - "teoli", - "goldWind", - "karsa.si" - ] - }, "Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria": { "modified": "2019-06-14T00:02:23.198Z", "contributors": [ @@ -37466,12 +37444,6 @@ "Jack-Q" ] }, - "Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { - "modified": "2020-03-12T19:46:27.376Z", - "contributors": [ - "WayneCui" - ] - }, "Web/JavaScript/Reference/Errors/Undeclared_var": { "modified": "2020-03-12T19:45:21.644Z", "contributors": [ @@ -50216,6 +50188,28 @@ "teoli" ] }, + "orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { + "modified": "2019-09-29T21:07:32.199Z", + "contributors": [ + "Nonym", + "Zaynex", + "nztraveler", + "hooozen", + "SphinxKnight", + "gaoryrt", + "WenWu92", + "Yongest", + "RyanBeauclerc", + "em2046", + "ywwzwb", + "ziyunfei", + "mountainmoon", + "Fify", + "teoli", + "goldWind", + "karsa.si" + ] + }, "orphaned/Web/API/MSSelection": { "modified": "2020-02-27T01:47:20.687Z", "contributors": [ @@ -50612,6 +50606,12 @@ "huangjihua" ] }, + "orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments": { + "modified": "2020-03-12T19:46:27.376Z", + "contributors": [ + "WayneCui" + ] + }, "orphaned/Web/JavaScript/Reference/Global_Objects/Array/prototype": { "modified": "2020-10-15T21:25:06.780Z", "contributors": [ diff --git a/files/zh-cn/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/zh-cn/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..3d61520d83 --- /dev/null +++ b/files/zh-cn/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,205 @@ +--- +title: 基本概念 +slug: orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +tags: + - IndexedDB 总述 +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +original_slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +
+

IndexedDB 是一种在用户浏览器中持久存储数据的方法。它允许您不考虑网络可用性,创建具有丰富查询能力的可离线 Web 应用程序。IndexedDB 对于存储大量数据的应用程序(例如借阅库中的 DVD 目录)和不需要持久 Internet 连接的应用程序(例如邮件客户端、待办事项列表或记事本)很有用。

+
+ +

关于本文档

+ +

本简介讨论了 IndexedDB 中的基本概念和术语。为您提供了概览并解释了关键概念。

+ +

您会发现以下非常有用的内容:

+ + + +

 IndexedDB概况

+ +

使用IndexedDB,你可以使用一个key作为索引进行存储或者获取数据。 你可以在事务(transaction)中完成对数据的修改。和大多数web存储解决方案相同,indexedDB也遵从同源协议(same-origin policy). 所以你只能访问同域中存储的数据,而不能访问其他域的。

+ +

IndexedDB 是一种异步(asynchronous) API,异步API适用于大多数情况,包括Web Workers。因为在Web Workers上的使用,它过去也有一个同步(synchronous)的版本,但是因为缺少web社区的支持,它已经被从规范中移除了。

+ +

IndexedDB 过去有一个竞争规范—— WebSQL 数据库,但是W3C组织在2010年11月18日废弃了webSql。尽管两者都是存储的解决方案,但是他们提供的不是同样的功能。IndexedDB 和WebSQL的不同点在于WebSQL 是关系型数据库访问系统,IndexedDB 是索引表系统(key-value型)。

+ +

基本概念

+ +

如果你因为使用其他类型数据库有某些固定思维,那么你在使用IndexedDB的时候可能会感到困惑,所以请牢记以下重要的概念:

+ + + +

名词解释

+ +

本节定义并解释了IndexedDB API中所使用的术语

+ +

数据库

+ +
+
数据库(database)
+
一个信息库,通常包含一个或多个 object stores. 每个数据库必须包含以下内容:
+
+
    +
  • 名字(Name)。它标识了一个特定源中的数据库,并且在数据库的整个生命周期内保持不变。  此名字可以为任意字符串值(包括空字符串)。
  • +
  • 当前版本(version)。当一个数据库首次创建时,它的 version 为1,除非另外指定. 每个数据库在任意时刻只能有一个 version。
  • +
+
+
持久性(durable)
+
在 Firefox 中,IndexedDB 是持久的,也就是说在一个读写事务中,一旦 IDBTransaction.oncomplete 事件被触发,就代表着数据已经确保被写入磁盘中了。
+
从 Firfox 40 起,IndexedDB 事务放松了对持久性的保证以提高性能(参见 Bug1112702),这与其他支持 IndexedDB 的浏览器的处理方式相同。在这种情况下,当操作系统被告知去写入数据后 complete 事件便被触发,但此时数据可能还没有真正的写入磁盘。事件触发因此变得更快,但这样会有极小的机会发生以下情况:如果操作系统崩溃或在数据被写入磁盘前断电,那么整个事务都将丢失。由于这种灾难事件是罕见的,大多数使用者并不需要过分担心。
+
对象仓库(object store)
+
+

数据在数据库中存储的方式, 数据以键值对形式被对象仓库永久持有。对象仓库中的的数据以 keys 升序排列。

+ +

每一个对象仓库在同一个数据库中必须有唯一的名字。对象存储可以有一个 key generator 和一个 key path如果对象仓库有 key path,则使用 in-line keys; 否则使用 out-of-line keys

+ +

关于对象仓库的详细文档,请参考 IDBObjectStore 或者 IDBObjectStoreSync

+
+
版本(version)
+
当第一次创建一个数据库,它的版本为整型1。每个数据库依次有一个版本号; 一个数据库不能同时存在多个版本号。改变版本的唯一方法是通过一个比当前版本号更高的值去打开数据库。这会开启一个 VERSION_CHANGE 事务并且触发 upgradeneeded 事件。只有在该事件的处理函数中才能更新数据库模式。
+
注意:这里的描述以最新规范为准,这些规范可能只在最新的浏览器中实现了。老旧的浏览器实现了现在已弃用和移除的 IDBDataBase.setVersion() 方法。
+
数据库连接(database connection)
+
通过打开数据库创建的操作。一个给定的数据库可以同时拥有多个连接。
+
事务(transaction)
+
在一个特定的数据库上,一组具备原子性和持久性的数据访问和数据修改的操作。它是你与数据库交互的方式。并且,任何对于数据库中的数据读和修改的操作只能在事务中进行。
+
+

一个数据库连接可以拥有多个与之关联的事务,只要进行写操作事务的作用域不相互重合。事务的作用域在事务被创建时就被确定,指定事务能够进行交互的对象仓库(object store),作用域一旦被确定就会在整个生命周期中保持不变。举个例子,如果一个数据库连接已经有了一个进行写操作的事务,其作用域覆盖 flyingMonkey 对象仓库,你可以开启新的事务其作用于 unicornCentaurunicornPegasus 对象仓库。对于读操作的事务,你可以同时拥有多个,即使他们有重叠的作用域。

+ +

事务被期望拥有较短的生命周期,所以浏览器会终止一个消耗时间过长的事务,为了释放存储资源,运行过久的事务会被锁定。你可以中断一个事务,来回滚事务中对数据库进行的操作。并且你甚至不需要等待事务开始或激活就可以中断它。

+ +

事务有三种模式:读写、只读和版本变更。创建和删除对象仓库(object store)的唯一方法就是通过调用版本变更事务。了解更多关于事务类型的内容,请参考 IndexedDB

+ +

因为所有的事情都在事务中发生,所以它是 IndexedDB 中非常重要的一个概念。了解更多关于事务,尤其是关于它和版本控制的关联,查看 IDBTransaction 中的参考文档。关于同步接口的文档,查看 IDBTransactionSync

+
+
请求(request)
+
在数据库上进行读写操作完成后的操作。每一个请求代表一个读或写操作。
+
索引(index)
+
+

一个对象仓库,专门用来查找另一个对象仓库(object store)中的记录,其中被查找的对象仓库被称为引用对象仓库。索引(index)是一个稳定的键值对(key-value)存储,其记录中的值(value)是引用对象仓库记录中的键(key)。当引用对象仓库中的记录新增、更新或删除时,索引中的记录会自动的进行粒子性增加。索引中的每一条记录只能指向引用对象仓库中的一条记录,但多个索引可以引用同一个对象仓库。当对象仓库发生改变时,所有引用该对象仓库的引用均会自动更新。

+ +

可选地,你也可以适用键(key)再对象仓库中查找记录。

+ +

了解更多关于如何适用索引,查看使用 IndexedDB。index 的参考文档查看 IDBKeyRange

+
+
+ +

键和值

+ +
+
键(key)
+
在对象仓库中阻止和检索被存储起来的值的数据值。数据仓库的键来源于以下三个方式之一:键生成器、键路径和显式指定的值。键必须是一种能够比较大小的数据类型。在同一个对象仓库中每条记录必须有一个独一无二的键,所以你不能在同一个对象仓库中为多个记录设置同样的键。
+
+

键可以是以下数据类型:字符串、日期、浮点和数组。对于数组,键的取值可以从空数组到无穷。并且你可以使用嵌套数组。注意,在 Firefox 11 之前的版本键只接受字符串和整形。

+ +

可选地,你也可以通过索引(index)来查找记录。

+
+
键生成器(key generator)
+
一种生成有序键的机制。如果一个对象仓库并不具备一个键生成器,那么应用程序必须为被存储的记录提供键。生成器在仓库之间并不共享。它更多的是浏览器的实现细节,因为在 Web 开发中你并不会真正的去创建或访问键生成器。
+
内键(in-line key)
+
作为存储值一部分的键。内键由键路径(key path)查找。内键由生成器生成。当内键生成后,它会被键路径存储在值中,它也可以被当作键使用。
+
外键(out-of-line key)
+
与值分开存储的键。
+
键路径(key path)
+
指定浏览器如何从对象仓库或索引存储的值中提取键。一个合法的键路径可以是以下形式:一个空字符串,一个 JavasScript 标识符,或由句点分割的多个 JavaScript 标识符。但不能包括空格。
+
值(value)
+
每条记录包含一个值,该值可以包含任何 JavaScript 表达式,包括:布尔数字字符串日期对象数组正则未定义和 null。
+
+

对于对象和数组,它们的属性和值也可以是任意合法的值。

+ +

规范允许你存储文件和二进制对象,但该标准只被 Firefox 11+ 实现。

+
+
+ +

范围和作用域

+ +
+
作用域(scope)
+
事务所作用的一组对象仓库或索引。只读事务的作用域可以相互重叠并同时执行操作。但写操作事务的作用域不可以相互重叠。但你仍然可以同时开启多个拥有相同作用域的事务,只要保证他们的操作不会同时执行。
+
游标(cursor)
+
在键的某个范围内迭代查询多条记录的机制。游标有一个指向正在被迭代的对象仓库或索引的源。它处于该范围内的一个位置,并按照键的顺序正向或逆向的移动。有关游标的参考文档,查看 IDBCursorIDBCursorSync
+
键范围(key range)
+
用做键的数据类型上的连续的间隔。使用键或键的某个范围可以从对象仓库和索引中读取记录。你可以通过上限和下限设置和筛选范围。比如,你可以遍历 x 和 y 之间所有的键值。
+
有关键范围的参考文档,查看 IDBKeyRange.
+
+ +

局限性

+ +

以下情况不适合使用IndexedDB

+ + + +

注意,在以下情况下,数据库可能被清除:

+ + + +

确切的环境和浏览器特性会随着时间改变,但浏览器厂商通常会遵循尽最大努力保留数据的理念。

+ +

下一步

+ +

查看如何使用的文档: Using IndexedDB.

+ +

相关文章

+ + diff --git a/files/zh-cn/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/zh-cn/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html new file mode 100644 index 0000000000..d53c093683 --- /dev/null +++ b/files/zh-cn/orphaned/web/javascript/reference/errors/typed_array_invalid_arguments/index.html @@ -0,0 +1,77 @@ +--- +title: 'TypeError: invalid arguments' +slug: orphaned/Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +tags: + - JavaScript + - 类型错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +original_slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: invalid arguments (Firefox)
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

类型化数组(Typed array) 的构造器可以通过接收以下类型的参数中的一种

+ + + +

来创建一个新的类型化数组。其他类型的构造器参数都无法创建合法的类型化数组。

+ +

示例

+ +

类型化数组——例如  {{jsxref("Uint8Array")}} ——无法通过字符串创建。实际上,字符串根本不能出现在类型化数组中。

+ +
var ta = new Uint8Array("nope");
+// TypeError: invalid arguments
+
+ +

创建一个合法的 {{jsxref("Uint8Array")}} 对象的不同方式:

+ +
// From a length
+var uint8 = new Uint8Array(2);
+uint8[0] = 42;
+console.log(uint8[0]); // 42
+console.log(uint8.length); // 2
+console.log(uint8.BYTES_PER_ELEMENT); // 1
+
+// From an array
+var arr = new Uint8Array([21,31]);
+console.log(arr[1]); // 31
+
+// From another TypedArray
+var x = new Uint8Array([21, 31]);
+var y = new Uint8Array(x);
+console.log(y[0]); // 21
+
+// From an ArrayBuffer
+var buffer = new ArrayBuffer(8);
+var z = new Uint8Array(buffer, 1, 4);
+
+// From an iterable
+var iterable = function*(){ yield* [1,2,3]; }();
+var uint8 = new Uint8Array(iterable);
+// Uint8Array[1, 2, 3]
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/zh-cn/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html deleted file mode 100644 index dfbfa97dd6..0000000000 --- a/files/zh-cn/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html +++ /dev/null @@ -1,204 +0,0 @@ ---- -title: 基本概念 -slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -tags: - - IndexedDB 总述 -translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB ---- -

{{DefaultAPISidebar("IndexedDB")}}

- -
-

IndexedDB 是一种在用户浏览器中持久存储数据的方法。它允许您不考虑网络可用性,创建具有丰富查询能力的可离线 Web 应用程序。IndexedDB 对于存储大量数据的应用程序(例如借阅库中的 DVD 目录)和不需要持久 Internet 连接的应用程序(例如邮件客户端、待办事项列表或记事本)很有用。

-
- -

关于本文档

- -

本简介讨论了 IndexedDB 中的基本概念和术语。为您提供了概览并解释了关键概念。

- -

您会发现以下非常有用的内容:

- - - -

 IndexedDB概况

- -

使用IndexedDB,你可以使用一个key作为索引进行存储或者获取数据。 你可以在事务(transaction)中完成对数据的修改。和大多数web存储解决方案相同,indexedDB也遵从同源协议(same-origin policy). 所以你只能访问同域中存储的数据,而不能访问其他域的。

- -

IndexedDB 是一种异步(asynchronous) API,异步API适用于大多数情况,包括Web Workers。因为在Web Workers上的使用,它过去也有一个同步(synchronous)的版本,但是因为缺少web社区的支持,它已经被从规范中移除了。

- -

IndexedDB 过去有一个竞争规范—— WebSQL 数据库,但是W3C组织在2010年11月18日废弃了webSql。尽管两者都是存储的解决方案,但是他们提供的不是同样的功能。IndexedDB 和WebSQL的不同点在于WebSQL 是关系型数据库访问系统,IndexedDB 是索引表系统(key-value型)。

- -

基本概念

- -

如果你因为使用其他类型数据库有某些固定思维,那么你在使用IndexedDB的时候可能会感到困惑,所以请牢记以下重要的概念:

- - - -

名词解释

- -

本节定义并解释了IndexedDB API中所使用的术语

- -

数据库

- -
-
数据库(database)
-
一个信息库,通常包含一个或多个 object stores. 每个数据库必须包含以下内容:
-
-
    -
  • 名字(Name)。它标识了一个特定源中的数据库,并且在数据库的整个生命周期内保持不变。  此名字可以为任意字符串值(包括空字符串)。
  • -
  • 当前版本(version)。当一个数据库首次创建时,它的 version 为1,除非另外指定. 每个数据库在任意时刻只能有一个 version。
  • -
-
-
持久性(durable)
-
在 Firefox 中,IndexedDB 是持久的,也就是说在一个读写事务中,一旦 IDBTransaction.oncomplete 事件被触发,就代表着数据已经确保被写入磁盘中了。
-
从 Firfox 40 起,IndexedDB 事务放松了对持久性的保证以提高性能(参见 Bug1112702),这与其他支持 IndexedDB 的浏览器的处理方式相同。在这种情况下,当操作系统被告知去写入数据后 complete 事件便被触发,但此时数据可能还没有真正的写入磁盘。事件触发因此变得更快,但这样会有极小的机会发生以下情况:如果操作系统崩溃或在数据被写入磁盘前断电,那么整个事务都将丢失。由于这种灾难事件是罕见的,大多数使用者并不需要过分担心。
-
对象仓库(object store)
-
-

数据在数据库中存储的方式, 数据以键值对形式被对象仓库永久持有。对象仓库中的的数据以 keys 升序排列。

- -

每一个对象仓库在同一个数据库中必须有唯一的名字。对象存储可以有一个 key generator 和一个 key path如果对象仓库有 key path,则使用 in-line keys; 否则使用 out-of-line keys

- -

关于对象仓库的详细文档,请参考 IDBObjectStore 或者 IDBObjectStoreSync

-
-
版本(version)
-
当第一次创建一个数据库,它的版本为整型1。每个数据库依次有一个版本号; 一个数据库不能同时存在多个版本号。改变版本的唯一方法是通过一个比当前版本号更高的值去打开数据库。这会开启一个 VERSION_CHANGE 事务并且触发 upgradeneeded 事件。只有在该事件的处理函数中才能更新数据库模式。
-
注意:这里的描述以最新规范为准,这些规范可能只在最新的浏览器中实现了。老旧的浏览器实现了现在已弃用和移除的 IDBDataBase.setVersion() 方法。
-
数据库连接(database connection)
-
通过打开数据库创建的操作。一个给定的数据库可以同时拥有多个连接。
-
事务(transaction)
-
在一个特定的数据库上,一组具备原子性和持久性的数据访问和数据修改的操作。它是你与数据库交互的方式。并且,任何对于数据库中的数据读和修改的操作只能在事务中进行。
-
-

一个数据库连接可以拥有多个与之关联的事务,只要进行写操作事务的作用域不相互重合。事务的作用域在事务被创建时就被确定,指定事务能够进行交互的对象仓库(object store),作用域一旦被确定就会在整个生命周期中保持不变。举个例子,如果一个数据库连接已经有了一个进行写操作的事务,其作用域覆盖 flyingMonkey 对象仓库,你可以开启新的事务其作用于 unicornCentaurunicornPegasus 对象仓库。对于读操作的事务,你可以同时拥有多个,即使他们有重叠的作用域。

- -

事务被期望拥有较短的生命周期,所以浏览器会终止一个消耗时间过长的事务,为了释放存储资源,运行过久的事务会被锁定。你可以中断一个事务,来回滚事务中对数据库进行的操作。并且你甚至不需要等待事务开始或激活就可以中断它。

- -

事务有三种模式:读写、只读和版本变更。创建和删除对象仓库(object store)的唯一方法就是通过调用版本变更事务。了解更多关于事务类型的内容,请参考 IndexedDB

- -

因为所有的事情都在事务中发生,所以它是 IndexedDB 中非常重要的一个概念。了解更多关于事务,尤其是关于它和版本控制的关联,查看 IDBTransaction 中的参考文档。关于同步接口的文档,查看 IDBTransactionSync

-
-
请求(request)
-
在数据库上进行读写操作完成后的操作。每一个请求代表一个读或写操作。
-
索引(index)
-
-

一个对象仓库,专门用来查找另一个对象仓库(object store)中的记录,其中被查找的对象仓库被称为引用对象仓库。索引(index)是一个稳定的键值对(key-value)存储,其记录中的值(value)是引用对象仓库记录中的键(key)。当引用对象仓库中的记录新增、更新或删除时,索引中的记录会自动的进行粒子性增加。索引中的每一条记录只能指向引用对象仓库中的一条记录,但多个索引可以引用同一个对象仓库。当对象仓库发生改变时,所有引用该对象仓库的引用均会自动更新。

- -

可选地,你也可以适用键(key)再对象仓库中查找记录。

- -

了解更多关于如何适用索引,查看使用 IndexedDB。index 的参考文档查看 IDBKeyRange

-
-
- -

键和值

- -
-
键(key)
-
在对象仓库中阻止和检索被存储起来的值的数据值。数据仓库的键来源于以下三个方式之一:键生成器、键路径和显式指定的值。键必须是一种能够比较大小的数据类型。在同一个对象仓库中每条记录必须有一个独一无二的键,所以你不能在同一个对象仓库中为多个记录设置同样的键。
-
-

键可以是以下数据类型:字符串、日期、浮点和数组。对于数组,键的取值可以从空数组到无穷。并且你可以使用嵌套数组。注意,在 Firefox 11 之前的版本键只接受字符串和整形。

- -

可选地,你也可以通过索引(index)来查找记录。

-
-
键生成器(key generator)
-
一种生成有序键的机制。如果一个对象仓库并不具备一个键生成器,那么应用程序必须为被存储的记录提供键。生成器在仓库之间并不共享。它更多的是浏览器的实现细节,因为在 Web 开发中你并不会真正的去创建或访问键生成器。
-
内键(in-line key)
-
作为存储值一部分的键。内键由键路径(key path)查找。内键由生成器生成。当内键生成后,它会被键路径存储在值中,它也可以被当作键使用。
-
外键(out-of-line key)
-
与值分开存储的键。
-
键路径(key path)
-
指定浏览器如何从对象仓库或索引存储的值中提取键。一个合法的键路径可以是以下形式:一个空字符串,一个 JavasScript 标识符,或由句点分割的多个 JavaScript 标识符。但不能包括空格。
-
值(value)
-
每条记录包含一个值,该值可以包含任何 JavaScript 表达式,包括:布尔数字字符串日期对象数组正则未定义和 null。
-
-

对于对象和数组,它们的属性和值也可以是任意合法的值。

- -

规范允许你存储文件和二进制对象,但该标准只被 Firefox 11+ 实现。

-
-
- -

范围和作用域

- -
-
作用域(scope)
-
事务所作用的一组对象仓库或索引。只读事务的作用域可以相互重叠并同时执行操作。但写操作事务的作用域不可以相互重叠。但你仍然可以同时开启多个拥有相同作用域的事务,只要保证他们的操作不会同时执行。
-
游标(cursor)
-
在键的某个范围内迭代查询多条记录的机制。游标有一个指向正在被迭代的对象仓库或索引的源。它处于该范围内的一个位置,并按照键的顺序正向或逆向的移动。有关游标的参考文档,查看 IDBCursorIDBCursorSync
-
键范围(key range)
-
用做键的数据类型上的连续的间隔。使用键或键的某个范围可以从对象仓库和索引中读取记录。你可以通过上限和下限设置和筛选范围。比如,你可以遍历 x 和 y 之间所有的键值。
-
有关键范围的参考文档,查看 IDBKeyRange.
-
- -

局限性

- -

以下情况不适合使用IndexedDB

- - - -

注意,在以下情况下,数据库可能被清除:

- - - -

确切的环境和浏览器特性会随着时间改变,但浏览器厂商通常会遵循尽最大努力保留数据的理念。

- -

下一步

- -

查看如何使用的文档: Using IndexedDB.

- -

相关文章

- - diff --git a/files/zh-cn/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/zh-cn/web/javascript/reference/errors/typed_array_invalid_arguments/index.html deleted file mode 100644 index 314a4a425c..0000000000 --- a/files/zh-cn/web/javascript/reference/errors/typed_array_invalid_arguments/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: 'TypeError: invalid arguments' -slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments -tags: - - JavaScript - - 类型错误 - - 错误提示 -translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments ---- -
{{jsSidebar("Errors")}}
- -

错误提示

- -
TypeError: invalid arguments (Firefox)
- -

错误类型

- -

{{jsxref("TypeError")}}

- -

哪里出错了?

- -

类型化数组(Typed array) 的构造器可以通过接收以下类型的参数中的一种

- - - -

来创建一个新的类型化数组。其他类型的构造器参数都无法创建合法的类型化数组。

- -

示例

- -

类型化数组——例如  {{jsxref("Uint8Array")}} ——无法通过字符串创建。实际上,字符串根本不能出现在类型化数组中。

- -
var ta = new Uint8Array("nope");
-// TypeError: invalid arguments
-
- -

创建一个合法的 {{jsxref("Uint8Array")}} 对象的不同方式:

- -
// From a length
-var uint8 = new Uint8Array(2);
-uint8[0] = 42;
-console.log(uint8[0]); // 42
-console.log(uint8.length); // 2
-console.log(uint8.BYTES_PER_ELEMENT); // 1
-
-// From an array
-var arr = new Uint8Array([21,31]);
-console.log(arr[1]); // 31
-
-// From another TypedArray
-var x = new Uint8Array([21, 31]);
-var y = new Uint8Array(x);
-console.log(y[0]); // 21
-
-// From an ArrayBuffer
-var buffer = new ArrayBuffer(8);
-var z = new Uint8Array(buffer, 1, 4);
-
-// From an iterable
-var iterable = function*(){ yield* [1,2,3]; }();
-var uint8 = new Uint8Array(iterable);
-// Uint8Array[1, 2, 3]
-
- -

相关内容

- - diff --git a/files/zh-tw/_redirects.txt b/files/zh-tw/_redirects.txt index 8cb3891190..998b521767 100644 --- a/files/zh-tw/_redirects.txt +++ b/files/zh-tw/_redirects.txt @@ -184,7 +184,7 @@ /zh-TW/docs/HTTP/X-Frame-Options /zh-TW/docs/Web/HTTP/Headers/X-Frame-Options /zh-TW/docs/HTTP/data_URIs /zh-TW/docs/Web/HTTP/Basics_of_HTTP/Data_URIs /zh-TW/docs/IndexedDB /zh-TW/docs/Web/API/IndexedDB_API -/zh-TW/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /zh-TW/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +/zh-TW/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /zh-TW/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /zh-TW/docs/IndexedDB/Using_IndexedDB /zh-TW/docs/Web/API/IndexedDB_API/Using_IndexedDB /zh-TW/docs/JavaScript /zh-TW/docs/Web/JavaScript /zh-TW/docs/JavaScript/About_JavaScript /zh-TW/docs/Web/JavaScript/About_JavaScript @@ -573,6 +573,7 @@ /zh-TW/docs/Web/API/Geolocation/Using_geolocation /zh-TW/docs/Web/API/Geolocation_API /zh-TW/docs/Web/API/HTMLElement/dataset /zh-TW/docs/Web/API/HTMLOrForeignElement/dataset /zh-TW/docs/Web/API/HTMLElement/style /zh-TW/docs/orphaned/Web/API/ElementCSSInlineStyle/style +/zh-TW/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /zh-TW/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /zh-TW/docs/Web/API/Node/innerText /zh-TW/docs/Web/API/HTMLElement/innerText /zh-TW/docs/Web/API/NonDocumentTypeChildNode /zh-TW/docs/conflicting/Web/API/Element /zh-TW/docs/Web/API/ParentNode /zh-TW/docs/orphaned/Web/API/ParentNode diff --git a/files/zh-tw/_wikihistory.json b/files/zh-tw/_wikihistory.json index be2ddcd06f..8590ffcd97 100644 --- a/files/zh-tw/_wikihistory.json +++ b/files/zh-tw/_wikihistory.json @@ -4121,16 +4121,6 @@ "princetoad@gmail.com" ] }, - "Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { - "modified": "2019-03-18T20:39:41.131Z", - "contributors": [ - "choznerol", - "jackblackevo", - "birdca", - "foxbrush", - "thomaschen" - ] - }, "Web/API/IndexedDB_API/Using_IndexedDB": { "modified": "2019-06-26T04:56:24.502Z", "contributors": [ @@ -8689,6 +8679,16 @@ "jackblackevo" ] }, + "orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB": { + "modified": "2019-03-18T20:39:41.131Z", + "contributors": [ + "choznerol", + "jackblackevo", + "birdca", + "foxbrush", + "thomaschen" + ] + }, "orphaned/Web/API/ParentNode": { "modified": "2019-12-24T08:07:24.128Z", "contributors": [ diff --git a/files/zh-tw/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/zh-tw/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..3b9da6d013 --- /dev/null +++ b/files/zh-tw/orphaned/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,210 @@ +--- +title: IndexedDB基礎概念 +slug: orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +original_slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

IndexedDB 用來儲存資料到使用者的瀏覽器,所以我們的網頁應用程式不論在線上或線下都可以運作。IndexedDB 對需要儲存大量資料上 (如儲存 DVD 出租型錄) 的應用和不用一直存取網路的應用 (如郵件客戶端瀏覽、代辦事項、記事本等) 來說十分好用。

+ +

關於本文

+ +

本文介紹 IndexedDB 重要概念和專有名詞,旨在提供 IndexedDB 全貌和關鍵概念,如要了解更多 IndexedDB 專有名詞,請參照定義部分。

+ +

想了解如何使用相關 API,請參照使用 IndexedDB;相關參考資料請參照 IndexedDB 一文,該文介紹了 IndexedDB 使用物件型態以及同步和非同步 API 。

+ +

IndexedDB 概要

+ +

IndexedDB 讓我們透過資料鍵 (key) 儲存、取回物件。所有對資料庫的變更都發生在交易操作;如同大部分網頁儲存方案,IndexedDB 遵守同源政策,也就是說我們只能存取同網域下的資料。

+ +

API 有分非同步同步,非同步 API 適用於大部分情況,包括 Web Worker,而同步 API 應該只用在 Web Worker 內。目前主流瀏覽器尚不支援同步 API,不過即使同步 API 存在,大部分的情況還是以非同步 API 使用為主。

+ +

W3C 在 2011/11/18 宣布 WebSQL 已棄用,請用 IndexedDB 作為替代方案。IndexedDB 和 WebSQL 雖然都是儲存方案,但功能並不相同,IndexedDB 是索引資料表資料庫,而 WebSQL 是關聯式資料庫系統。

+ +

概念總覽

+ +

請將你在其他類型資料庫上的預期從 IndexedDB 上拋開,然後謹記以下重要概念:

+ + + +

定義

+ +

以下是 IndexedDB API 專有名詞定義與解說。

+ +

Database

+ +
+
資料庫
+
資訊集中存放之處,由一或數個物件存檔 (Object store) 組成,每一個資料庫必須具有: +
    +
  • 名稱。用以辨識資料庫所屬來源,在生命週期間固定不變,可以任意字串 (甚至空白字串) 。
  • +
  • +

    目前版本。當資料庫創建後,如未指定,它的版本是整數1。每一個資料庫同一時間只能有一個版本。

    +
  • +
+
+
物件存檔 (object store)
+
+

資料存放於資料庫的機制;物件存檔持有紀錄,也就是資料鍵和資料值的成對紀錄。記錄在物件存檔中依資料鍵 (keys)大小由小到大排列。

+ +

每一個物件存檔都具備獨特名稱,物件存檔能夠選擇性地持有 key generator 和 key path;若有 key path 便會採用 in-line keys,否則便採用 out-of-line keys

+ +

更多物件存檔細節,請參照 IDBObjectStore 或 IDBObjectStoreSync

+
+
版本 (version)
+
當資料庫創建後,如未指定,它的版本是整數 1;每一個資料庫同一時間只能有一個版本,唯一變更版本的方法是開啟比目前更大的版本,變更版本將啟動 versionchange 交易並且觸發 upgradeneeded 事件,upgradeneeded 事件處理器也是唯一可以變更資料庫結構之處。
+
注意: 本處解說涵蓋近期大部分規範,舊版瀏覽器支援現在已經廢棄的 IDBDatabase.setVersion() 方法。
+
 
+
database connection
+
開啟資料庫的作業,一個資料庫同一時間可以擁有多個連線。
+
交易 (transaction)
+
+

在特定資料庫上進行資料存取和資料修改的一連串作業,這便是我們和資料庫的互動,事實上,任何讀取或變更資料庫資料都會發生在交易之中。

+ +

只要寫入交易間沒有重疊範疇 (scopes),一個資料庫連結可以同時擁有多個進行中交易。交易範疇在交易創建當下決定,交易範疇定義了與交易互動的物件存檔以及將交易期間不可變更部分,例如說,有一個資料庫連結正在進行寫入交易,這項寫入交易涵蓋 flyingMonkey 物件存檔,我們可以進行第二項有關 unicornCentaur 與 unicornPegasus 物件存檔的交易。至於讀取交易則不受交易範疇重疊限制。

+ +

交易的生命應該不可過長,所以瀏覽器可以終止交易時間過長的交易,好讓長時間被鎖定的資料得以解除鎖定;交易可以中止,中止後交易所造成的變更都會被復原;交易的中止不必要等到交易開始或進行中。

+ +

交易有三種模式: readwrite, readonly 和 versionchange,只能透過 versionchange 交易創建、刪除物件存檔與索引。

+ +

由於交易是相當重要的觀念,尤其是交易和版本間的關係,請參照 IDBTransaction 以了解更多交易相
+ 關細節,另外關於同步API,請參照IDBTransactionSync

+
+
請求 (request)
+
每一個讀寫作業都是一個請求。
+
索引 (index)
+
+

一個用來查詢其他物件存檔內紀錄的特殊物件存檔,被查詢的物件存檔我們稱為參照物件存檔 (referenced object store) 。索引是資料鍵和值的成對紀錄,其中值就是參照物件存檔內的記錄的資料鍵;當參照物件存檔有紀錄新增、變更或刪除時索引內的紀錄也會相應自動產生,索引內的紀錄只能指向參照物件存檔內的一筆紀錄,但可以有多筆索引紀錄參照同一個物件存檔。物件存檔變更同時,所有的相關索引也會自動相應更新。

+ +

除此之外,我們也可以透過資料鍵 (key) 來查詢物件存檔中的紀錄。

+ +

了解如何使用索引請參照使用 IndexedDB,要知道更多索引細節請參照 IDBKeyRange 和 IDBIndex 。

+
+
+ +

資料鍵 (Key) 和資料值 (Value)

+ +
+
資料鍵 (key)
+
+

資料存放在物件存檔中。物件存檔有三種方式產生資料鍵: 資料鍵產生器 (key generator)、資料鍵路徑 (key path) 以及指定值。資料鍵的資料型態 (data type) 必須要是能夠進行大小排序;物件存檔中的每一筆紀錄都要有一支獨特的對應資料鍵,不能和同一個物件存檔中其他紀錄的資料鍵相同。

+ +

資料鍵可以是: string, date, float和 array (陣列);對於 array,資料鍵範圍可以是空值到無限,還可以在 array 中包含另一個 array,至於以字串或整數作資料鍵則無特殊規定。

+ +

除此之外,我們也可以透過索引 (index) 來查詢物件存檔中的紀錄。

+
+
資料鍵產生器 (key generator)
+
自動生成有大小順序關係的資料鍵的機制;因為資料鍵是必要的,所以如果沒有資料鍵或想省去給定資料鍵的步驟,那就需要用產生器自動產生資料鍵。
+
in-line key
+
當物件存檔有資料鍵路徑時稱為有使用 in-line key。
+
out-of-line key
+
當物件存檔沒有資料鍵路徑時稱為使用 out-of--line key。
+
資料鍵路徑 (key path)
+
定義瀏覽器應該如何從物件存檔資料值或索引中提取資料鍵。以下為有效的資料鍵路徑: 一個空字串、一個 Javascript 辨識名稱 (JavaScript identifier) 或數個由”.”(ASCII字元第46字碼) 分隔的 Javascript 辨識名稱。路徑不可含有空白字元。
+
資料值 (value)
+
+

每筆紀錄都有資料值,資料值可以是任意Javascript所能表達的項目,包括boolean, number, string, date, object, array, regexp, undefined 以及 null。

+ +

儲存物件或陣列裡的屬性和值也可以是任意Javascript所能表達的項目。

+ +

可以儲存 Blobs 和檔案,請參照 W3C 規範

+
+
+ +

範圍和範疇

+ +
+
範疇
+
交易影響到的物件和索引。讀取交易間的範疇可以互相重疊、同時進行,然後寫入交易範疇則不可,如果同時開啟多項交易範疇相同的寫入交易的話,那麼這些交易會排入佇列 (queue),一個接著一個完成後執行。
+
指標 (Cursor)
+
在一定資料鍵範圍以內往覆 (iterate) 資料的機制。指標指向了一個物件存檔或索引,它會在一定範圍內,由小到大或由大到小循著紀錄的資料鍵移動,詳細資訊請參照 IDBCursor 或 IDBCursorSync 。
+
資料鍵範圍
+
+

某種資料型態的一段連續區間,這個區間將作為資料鍵的上下限,我們透過資料鍵或資料鍵範圍取出物件存檔和索引值;藉由上下限我們可以做到存取資料鍵介於 x 和 y 之間的資料,詳細請參考 IDBKeyRange 。

+
+
+ +

限制

+ +

IndexedDB 設計上足以滿足大部分客戶端儲存需求,不過,以下情況並不適用 IndexedDB :

+ + + +

除此之外,請小心瀏覽器可能會清空資料庫,例如:

+ + + +

瀏覽器確切的狀況和功能範疇未來會變更,但基本上瀏覽器還是會盡可能保存資料。

+ +

下一步

+ +

現在我們已經了解 IndexedDB 的整體概念,接下來請到 “使用 IndexedDB” 看看如何實際使用 IndexedDB。

+ +

延伸閱讀

+ +

標準規範

+ + + +

參照

+ + + +

相關教學

+ + + +

相關文章

+ + diff --git a/files/zh-tw/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/zh-tw/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html deleted file mode 100644 index a57486e7b2..0000000000 --- a/files/zh-tw/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html +++ /dev/null @@ -1,209 +0,0 @@ ---- -title: IndexedDB基礎概念 -slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB -translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB ---- -

IndexedDB 用來儲存資料到使用者的瀏覽器,所以我們的網頁應用程式不論在線上或線下都可以運作。IndexedDB 對需要儲存大量資料上 (如儲存 DVD 出租型錄) 的應用和不用一直存取網路的應用 (如郵件客戶端瀏覽、代辦事項、記事本等) 來說十分好用。

- -

關於本文

- -

本文介紹 IndexedDB 重要概念和專有名詞,旨在提供 IndexedDB 全貌和關鍵概念,如要了解更多 IndexedDB 專有名詞,請參照定義部分。

- -

想了解如何使用相關 API,請參照使用 IndexedDB;相關參考資料請參照 IndexedDB 一文,該文介紹了 IndexedDB 使用物件型態以及同步和非同步 API 。

- -

IndexedDB 概要

- -

IndexedDB 讓我們透過資料鍵 (key) 儲存、取回物件。所有對資料庫的變更都發生在交易操作;如同大部分網頁儲存方案,IndexedDB 遵守同源政策,也就是說我們只能存取同網域下的資料。

- -

API 有分非同步同步,非同步 API 適用於大部分情況,包括 Web Worker,而同步 API 應該只用在 Web Worker 內。目前主流瀏覽器尚不支援同步 API,不過即使同步 API 存在,大部分的情況還是以非同步 API 使用為主。

- -

W3C 在 2011/11/18 宣布 WebSQL 已棄用,請用 IndexedDB 作為替代方案。IndexedDB 和 WebSQL 雖然都是儲存方案,但功能並不相同,IndexedDB 是索引資料表資料庫,而 WebSQL 是關聯式資料庫系統。

- -

概念總覽

- -

請將你在其他類型資料庫上的預期從 IndexedDB 上拋開,然後謹記以下重要概念:

- - - -

定義

- -

以下是 IndexedDB API 專有名詞定義與解說。

- -

Database

- -
-
資料庫
-
資訊集中存放之處,由一或數個物件存檔 (Object store) 組成,每一個資料庫必須具有: -
    -
  • 名稱。用以辨識資料庫所屬來源,在生命週期間固定不變,可以任意字串 (甚至空白字串) 。
  • -
  • -

    目前版本。當資料庫創建後,如未指定,它的版本是整數1。每一個資料庫同一時間只能有一個版本。

    -
  • -
-
-
物件存檔 (object store)
-
-

資料存放於資料庫的機制;物件存檔持有紀錄,也就是資料鍵和資料值的成對紀錄。記錄在物件存檔中依資料鍵 (keys)大小由小到大排列。

- -

每一個物件存檔都具備獨特名稱,物件存檔能夠選擇性地持有 key generator 和 key path;若有 key path 便會採用 in-line keys,否則便採用 out-of-line keys

- -

更多物件存檔細節,請參照 IDBObjectStore 或 IDBObjectStoreSync

-
-
版本 (version)
-
當資料庫創建後,如未指定,它的版本是整數 1;每一個資料庫同一時間只能有一個版本,唯一變更版本的方法是開啟比目前更大的版本,變更版本將啟動 versionchange 交易並且觸發 upgradeneeded 事件,upgradeneeded 事件處理器也是唯一可以變更資料庫結構之處。
-
注意: 本處解說涵蓋近期大部分規範,舊版瀏覽器支援現在已經廢棄的 IDBDatabase.setVersion() 方法。
-
 
-
database connection
-
開啟資料庫的作業,一個資料庫同一時間可以擁有多個連線。
-
交易 (transaction)
-
-

在特定資料庫上進行資料存取和資料修改的一連串作業,這便是我們和資料庫的互動,事實上,任何讀取或變更資料庫資料都會發生在交易之中。

- -

只要寫入交易間沒有重疊範疇 (scopes),一個資料庫連結可以同時擁有多個進行中交易。交易範疇在交易創建當下決定,交易範疇定義了與交易互動的物件存檔以及將交易期間不可變更部分,例如說,有一個資料庫連結正在進行寫入交易,這項寫入交易涵蓋 flyingMonkey 物件存檔,我們可以進行第二項有關 unicornCentaur 與 unicornPegasus 物件存檔的交易。至於讀取交易則不受交易範疇重疊限制。

- -

交易的生命應該不可過長,所以瀏覽器可以終止交易時間過長的交易,好讓長時間被鎖定的資料得以解除鎖定;交易可以中止,中止後交易所造成的變更都會被復原;交易的中止不必要等到交易開始或進行中。

- -

交易有三種模式: readwrite, readonly 和 versionchange,只能透過 versionchange 交易創建、刪除物件存檔與索引。

- -

由於交易是相當重要的觀念,尤其是交易和版本間的關係,請參照 IDBTransaction 以了解更多交易相
- 關細節,另外關於同步API,請參照IDBTransactionSync

-
-
請求 (request)
-
每一個讀寫作業都是一個請求。
-
索引 (index)
-
-

一個用來查詢其他物件存檔內紀錄的特殊物件存檔,被查詢的物件存檔我們稱為參照物件存檔 (referenced object store) 。索引是資料鍵和值的成對紀錄,其中值就是參照物件存檔內的記錄的資料鍵;當參照物件存檔有紀錄新增、變更或刪除時索引內的紀錄也會相應自動產生,索引內的紀錄只能指向參照物件存檔內的一筆紀錄,但可以有多筆索引紀錄參照同一個物件存檔。物件存檔變更同時,所有的相關索引也會自動相應更新。

- -

除此之外,我們也可以透過資料鍵 (key) 來查詢物件存檔中的紀錄。

- -

了解如何使用索引請參照使用 IndexedDB,要知道更多索引細節請參照 IDBKeyRange 和 IDBIndex 。

-
-
- -

資料鍵 (Key) 和資料值 (Value)

- -
-
資料鍵 (key)
-
-

資料存放在物件存檔中。物件存檔有三種方式產生資料鍵: 資料鍵產生器 (key generator)、資料鍵路徑 (key path) 以及指定值。資料鍵的資料型態 (data type) 必須要是能夠進行大小排序;物件存檔中的每一筆紀錄都要有一支獨特的對應資料鍵,不能和同一個物件存檔中其他紀錄的資料鍵相同。

- -

資料鍵可以是: string, date, float和 array (陣列);對於 array,資料鍵範圍可以是空值到無限,還可以在 array 中包含另一個 array,至於以字串或整數作資料鍵則無特殊規定。

- -

除此之外,我們也可以透過索引 (index) 來查詢物件存檔中的紀錄。

-
-
資料鍵產生器 (key generator)
-
自動生成有大小順序關係的資料鍵的機制;因為資料鍵是必要的,所以如果沒有資料鍵或想省去給定資料鍵的步驟,那就需要用產生器自動產生資料鍵。
-
in-line key
-
當物件存檔有資料鍵路徑時稱為有使用 in-line key。
-
out-of-line key
-
當物件存檔沒有資料鍵路徑時稱為使用 out-of--line key。
-
資料鍵路徑 (key path)
-
定義瀏覽器應該如何從物件存檔資料值或索引中提取資料鍵。以下為有效的資料鍵路徑: 一個空字串、一個 Javascript 辨識名稱 (JavaScript identifier) 或數個由”.”(ASCII字元第46字碼) 分隔的 Javascript 辨識名稱。路徑不可含有空白字元。
-
資料值 (value)
-
-

每筆紀錄都有資料值,資料值可以是任意Javascript所能表達的項目,包括boolean, number, string, date, object, array, regexp, undefined 以及 null。

- -

儲存物件或陣列裡的屬性和值也可以是任意Javascript所能表達的項目。

- -

可以儲存 Blobs 和檔案,請參照 W3C 規範

-
-
- -

範圍和範疇

- -
-
範疇
-
交易影響到的物件和索引。讀取交易間的範疇可以互相重疊、同時進行,然後寫入交易範疇則不可,如果同時開啟多項交易範疇相同的寫入交易的話,那麼這些交易會排入佇列 (queue),一個接著一個完成後執行。
-
指標 (Cursor)
-
在一定資料鍵範圍以內往覆 (iterate) 資料的機制。指標指向了一個物件存檔或索引,它會在一定範圍內,由小到大或由大到小循著紀錄的資料鍵移動,詳細資訊請參照 IDBCursor 或 IDBCursorSync 。
-
資料鍵範圍
-
-

某種資料型態的一段連續區間,這個區間將作為資料鍵的上下限,我們透過資料鍵或資料鍵範圍取出物件存檔和索引值;藉由上下限我們可以做到存取資料鍵介於 x 和 y 之間的資料,詳細請參考 IDBKeyRange 。

-
-
- -

限制

- -

IndexedDB 設計上足以滿足大部分客戶端儲存需求,不過,以下情況並不適用 IndexedDB :

- - - -

除此之外,請小心瀏覽器可能會清空資料庫,例如:

- - - -

瀏覽器確切的狀況和功能範疇未來會變更,但基本上瀏覽器還是會盡可能保存資料。

- -

下一步

- -

現在我們已經了解 IndexedDB 的整體概念,接下來請到 “使用 IndexedDB” 看看如何實際使用 IndexedDB。

- -

延伸閱讀

- -

標準規範

- - - -

參照

- - - -

相關教學

- - - -

相關文章

- - -- cgit v1.2.3-54-g00ecf