Skip to content

Commit dc2c28c

Browse files
authored
feat:translate article.md
1 parent eb19c07 commit dc2c28c

File tree

1 file changed

+97
-101
lines changed

1 file changed

+97
-101
lines changed

Diff for: 6-data-storage/02-localstorage/article.md

+97-101
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,55 @@
1-
# LocalStorage, sessionStorage
1+
# LocalStorage, sessionStorage
22

3-
Web storage objects `localStorage` and `sessionStorage` allow to save key/value pairs in the browser.
3+
Web 存储对象 `localStorage` `sessionStorage` 允许你在浏览器上保存键值对。
44

5-
What's interesting about them is that the data survives a page refresh (for `sessionStorage`) and even a full browser restart (for `localStorage`). We'll see that very soon.
5+
有趣的是,数据在页面刷新 (`sessionStorage`) 甚至浏览器完全重启 (`localStorage`) 后仍然保留。我们很快会看到。
66

7-
We already have cookies. Why additional objects?
7+
我们已经有了 `cookies`。为什么还要额外的 web 存储对象?
88

9-
- Unlike cookies, web storage objects are not sent to server with each request. Because of that, we can store much more. Most browsers allow at least 2 megabytes of data (or more) and have settings to configure that.
10-
- Also unlike cookies, the server can't manipulate storage objects via HTTP headers. Everything's done in JavaScript.
11-
- The storage is bound to the origin (domain/protocol/port triplet). That is, different protocols or subdomains infer different storage objects, they can't access data from each other.
9+
- `cookies` 不同,web 存储对象不会随着每次请求发送到服务端。因此,我们可以保存更多数据。大部分浏览器允许保存至少 2M 字节的数据 (或者更多),并且是可配置的。
10+
- 还有一点和 `cookies` 不同,服务端不能通过 HTTP 头部操作存储对象。一切都在 `JavaScript` 中完成。
11+
- 存储对象的来源绑定在 `域/协议/端口 三者之一` 下,也就是说,不同协议或者子域保存不同的存储对象,它们不能相互访问数据。
1212

13-
Both storage objects provide same methods and properties:
13+
两个存储对象都提供相同的方法和属性:
1414

15-
- `setItem(key, value)` -- store key/value pair.
16-
- `getItem(key)` -- get the value by key.
17-
- `removeItem(key)` -- remove the key with its value.
18-
- `clear()` -- delete everything.
19-
- `key(index)` -- get the key on a given position.
20-
- `length` -- the number of stored items.
15+
- `setItem(key, value)` -- 存储键值对。
16+
- `getItem(key)` -- 根据键名获取相应的值。
17+
- `removeItem(key)` -- 删除该键对应的键值对。
18+
- `clear()` -- 清空存储。
19+
- `key(index)` -- 获取该索引下的键名。
20+
- `length` -- 存储对象的长度。
2121

22-
As you can see, it's like a `Map` collection (`setItem/getItem/removeItem`), but also keeps elements order and allows to access by index with `key(index)`.
22+
正如你所看到的,它就像一个 `Map` 收集器 (`setItem/getItem/removeItem`)。但是也保持着元素顺序,并且允许通过索引访问 `key(index)`
2323

24-
Let's see how it works.
24+
让我们看看它是如何工作的。
2525

26-
## localStorage demo
26+
## localStorage 示例
2727

28-
The main features of `localStorage` are:
28+
`localStorage` 最主要的特点是:
2929

30-
- Shared between all tabs and windows from the same origin.
31-
- The data does not expire. It remains after the browser restart and even OS reboot.
30+
- 来自同一来源的数据在所有标签和窗口之间共享。
31+
- 数据不会过期。它在浏览器重启甚至系统重启后仍然保留。
3232

33-
For instance, if you run this code...
33+
例如,如果你运行此代码…
3434

3535
```js run
3636
localStorage.setItem('test', 1);
3737
```
3838

39-
...And close/open the browser or just open the same page in a different window, then you can get it like this:
39+
然后关闭重新打开浏览器或者只是在不同的窗口打开同一页面,然后你就能看到:
4040

4141
```js run
4242
alert( localStorage.getItem('test') ); // 1
4343
```
4444

45-
We only have to be on the same origin (domain/port/protocol), the url path can be different.
45+
我们只要求数据存储在同一域/端口/协议上,`url` 路径可以是不同的。
4646

47-
The `localStorage` is shared between all windows with the same origin, so if we set the data in one window, the change becomes visible in another one.
47+
`localStorage` 在相同来源下的所有窗口都是共享的。所以,如果我们在其中一个窗口设置了数据,在另外一个窗口中可以看到数据也发生了变化。
4848

49-
## Object-like access
5049

51-
We can also use a plain object way of getting/setting keys, like this:
50+
## 类似对象形式访问
51+
52+
我们也可以使用普通对象读取/设置键的方式,像这样:
5253

5354
```js run
5455
// set key
@@ -61,23 +62,18 @@ alert( localStorage.test ); // 2
6162
delete localStorage.test;
6263
```
6364

64-
That's allowed for historical reasons, and mostly works, but generally not recommended for two reasons:
65-
66-
1. If the key is user-generated, it can be anything, like `length` or `toString`, or another built-in method of `localStorage`. In that case `getItem/setItem` work fine, while object-like access fails:
67-
```js run
68-
let key = 'length';
69-
localStorage[key] = 5; // Error, can't assign length
70-
```
65+
这是历史原因允许的,并且大部分是有效的。但是通常不推荐这种做法,有两个原因:
7166

72-
2. There's a `storage` event, it triggers when we modify the data. That event does not happen for object-like access. We'll see that later in this chapter.
67+
1. 如果键是由用户生成的,那么它可以是任何内容,例如 `length``toString`,或者是 `localStorage` 下其他的内置方法。在这种情况下,`getItem/setItem` 可以正常使用,类似对象访问的方式则会失败。
68+
2. 有一个 `storage` 事件,在我们改变数据时会触发。但是以类似对象形式访问时,该事件不会触发。我们可以在本章节后面看到。
7369

74-
## Looping over keys
70+
## 循环键
7571

76-
As we've seen, the methods provide "get/set/remove by key" functionality. But how to get all saved values or keys?
72+
正如我们看到的,这些方法提供了按键获取/设置/删除的功能。但是我们怎么能够保存所有的值或者键呢?
7773

78-
Unfortunately, storage objects are not iterable.
74+
不幸的是,存储对象不可迭代。
7975

80-
One way is to loop over them as over an array:
76+
一种方法是在数组上循环遍历它们:
8177

8278
```js run
8379
for(let i=0; i<localStorage.length; i++) {
@@ -86,29 +82,29 @@ for(let i=0; i<localStorage.length; i++) {
8682
}
8783
```
8884

89-
Another way is to use `for key in localStorage` loop, just as we do with regular objects.
85+
另一个方法是使用 `for key in localStorage` 循环,就像我们循环普通对象一样。
9086

91-
It iterates over keys, but also outputs few built-in fields that we don't need:
87+
它循环所有的键,但是也输出了我们不需要的的几个内置字段。
9288

9389
```js run
9490
// bad try
9591
for(let key in localStorage) {
96-
alert(key); // shows getItem, setItem and other built-in stuff
92+
alert(key); // 显示 getItemsetItem 和其他内置函数
9793
}
9894
```
9995

100-
...So we need either to filter fields from the prototype with `hasOwnProperty` check:
96+
所以我们需要使用 `hasOwnProperty` 来过滤掉原型中的字段:
10197

10298
```js run
10399
for(let key in localStorage) {
104100
if (!localStorage.hasOwnProperty(key)) {
105-
continue; // skip keys like "setItem", "getItem" etc
101+
continue; // 跳过键,如 setItemgetItem
106102
}
107103
alert(`${key}: ${localStorage.getItem(key)}`);
108104
}
109105
```
110106

111-
...Or just get the "own" keys with `Object.keys` and then loop over them if needed:
107+
或者使用 `Object.keys` 获取本身的键,然后根据需要循环它:
112108

113109
```js run
114110
let keys = Object.keys(localStorage);
@@ -117,21 +113,20 @@ for(let key of keys) {
117113
}
118114
```
119115

120-
The latter works, because `Object.keys` only returns the keys that belong to the object, ignoring the prototype.
121-
116+
后者有效,因为 `Object.keys` 只返回属于对象的键,忽略原型。
122117

123-
## Strings only
118+
## 只有字符串
124119

125-
Please note that both key and value must be strings.
120+
请注意键和值都必须是字符串。
126121

127-
If were any other type, like a number, or an object, it gets converted to string automatically:
122+
如果是其他类型,例如数字或对象,它将自动转换为字符串。
128123

129124
```js run
130125
sessionStorage.user = {name: "John"};
131126
alert(sessionStorage.user); // [object Object]
132127
```
133128

134-
We can use `JSON` to store objects though:
129+
我们可以使用 `JSON` 来存储对象:
135130

136131
```js run
137132
sessionStorage.user = JSON.stringify({name: "John"});
@@ -141,67 +136,66 @@ let user = JSON.parse( sessionStorage.user );
141136
alert( user.name ); // John
142137
```
143138

144-
Also it is possible to stringify the whole storage object, e.g. for debugging purposes:
139+
为了调试的话,也可以将整个存储对象转为字符串。
145140

146141
```js run
147142
// added formatting options to JSON.stringify to make the object look nicer
148143
alert( JSON.stringify(localStorage, null, 2) );
149144
```
150145

151-
152146
## sessionStorage
153147

154-
The `sessionStorage` object is used much less often than `localStorage`.
148+
`sessionStorage` 的使用频率比 `localStorage` 少。
155149

156-
Properties and methods are the same, but it's much more limited:
150+
属性和方法是相同的,但是它具有更多的局限性:
157151

158-
- The `sessionStorage` exists only within the current browser tab.
159-
- Another tab with the same page will have a different storage.
160-
- But it is shared between iframes in the tab (assuming they come from the same origin).
161-
- The data survives page refresh, but not closing/opening the tab.
152+
- `sessionStorage` 只存在于当前浏览器标签页。
153+
- 具有相同页面的另外一个浏览器标签页中将会有不同的存储。
154+
- 但是它在当前标签页下的 `iframes` 之间是共享的(假如它们是同一来源)。
155+
- 数据在页面刷新后还保留,但是在关闭重新打开浏览器标签页后不会被保留。
162156

163-
Let's see that in action.
157+
让我们看看它是怎么运行的。
164158

165-
Run this code...
159+
运行此代码…
166160

167161
```js run
168162
sessionStorage.setItem('test', 1);
169163
```
170164

171-
...Then refresh the page. Now you can still get the data:
165+
然后刷新页面。这时候你还是可以获取到数据:
172166

173167
```js run
174168
alert( sessionStorage.getItem('test') ); // after refresh: 1
175169
```
176170

177-
...But if you open the same page in another tab, and try again there, the code above returns `null`, meaning "nothing found".
171+
但是如果你在新的标签页中打开此页面,然后在新的页面中运行以上代码,则会返回 `null`,意思是找不到数据。
178172

179-
That's exactly because `sessionStorage` is bound not only to the origin, but also to the browser tab. For that reason, `sessionStorage` is used sparingly.
173+
这是因为是 `sessionStorage` 不仅仅要求数据同源,还需要在同一浏览器标签页下。因此,请谨慎使用 `sessionStorage`
180174

181-
## Storage event
175+
## Storage 事件
182176

183-
When the data gets updated in `localStorage` or `sessionStorage`, [storage](https://www.w3.org/TR/webstorage/#the-storage-event) event triggers, with properties:
177+
`localStorage` `sessionStorage` 中的数据更新后,[storage 事件](https://www.w3.org/TR/webstorage/#the-storage-event)将会触发,具有以下特征:
184178

185-
- `key` – the key that was changed (`null` if `.clear()` is called).
186-
- `oldValue` – the old value (`null` if the key is newly added).
187-
- `newValue` – the new value (`null` if the key is removed).
188-
- `url` – the url of the document where the update happened.
189-
- `storageArea` – either `localStorage` or `sessionStorage` object where the update happened.
179+
- `key` `key` 将会被改变(如果调用的是 `.clear()` 方法,`key` 会返回 `null`)。
180+
- `oldValue` — 旧值(如果是新增 `key`,会返回 `null`)。
181+
- `newValue` — 新值(如果是删除 `key`,会返回 `null`)。
182+
- `url` — 数据发生更新时的文档链接。
183+
- `storageArea` — 数据发生更新的任何一个 `localStorage` `sessionStorage` 对象。
190184

191-
The important thing is: the event triggers on all `window` objects where the storage is accessible, except the one that caused it.
185+
最重要的是:事件将会在所有能访问到当前存储对象的 `window` 下触发,除了当前触发了事件的 `window`
192186

193-
Let's elaborate.
187+
我们来详细说明一下。
194188

195-
Imagine, you have two windows with the same site in each. So `localStorage` is shared between them.
189+
想象一下,你有两个两个窗口,每个窗口都有相同的页面。所以 `localStorage` 在它们之间是共享的。
196190

197191
```online
198-
You might want to open this page in two browser windows to test the code below.
192+
你可以在两个浏览器窗口中打开当前页面来测试下面的代码。
199193
```
200194

201-
If both windows are listening for `window.onstorage`, then each one will react on updates that happened in the other one.
195+
如果两个窗口都监听 `window.onstorage` 事件,那么每个窗口的事件将会在另外一个窗口中数据更新后被触发。
202196

203197
```js run
204-
// triggers on updates made to the same storage from other documents
198+
// 在另外一个具有相同存储对象更新后触发
205199
window.onstorage = event => {
206200
if (event.key != 'now') return;
207201
alert(event.key + ':' + event.newValue + " at " + event.url);
@@ -210,40 +204,42 @@ window.onstorage = event => {
210204
localStorage.setItem('now', Date.now());
211205
```
212206

213-
Please note that the event also contains: `event.url` -- the url of the document where the data was updated.
207+
请注意,该事件还包括 `event.url` -- 数据更新时的文档链接。
208+
209+
此外,`event.storageArea` 还会返回存储对象 -- 因为 `sessionStorage``localStorage` 具有相同的事件,所以 `storageArea` 会返回数据更新了的那一个存储对象。为了响应数据更新,我们也许会在里面设置一些东西。
210+
211+
** 这允许来自相同来源的不同窗口交换消息。 **
214212

215-
Also, `event.storageArea` contains the storage object -- the event is the same for both `sessionStorage` and `localStorage`, so `storageArea` references the one that was modified. We may even want to set something back in it, to "respond" to a change.
213+
现代浏览器还支持 [Broadcast channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API),这是用于同源窗口之间通信的特殊 API,它的功能更加全面,但是兼容性还不好。有一些库可以基于 `localStorage` polyfill 该 API,使其可以用在任何地方。
216214

217-
**That allows different windows from the same origin to exchange messages.**
218215

219-
Modern browsers also support [Broadcast channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API), the special API for same-origin inter-window communication, it's more full featured, but less supported. There are libraries that polyfill that API, based on `localStorage`, that make it available everywhere.
216+
## 总结
220217

221-
## Summary
218+
Web 存储对象 `localStorage``sessionStorage` 允许我们在浏览器中保存键值对。
222219

223-
Web storage objects `localStorage` and `sessionStorage` allow to store key/value in the browser.
224-
- Both `key` and `value` must be strings.
225-
- The limit is 2mb+, depends on the browser.
226-
- They do not expire.
227-
- The data is bound to the origin (domain/port/protocol).
220+
- 所有的 `key``value` 都必须是字符串。
221+
- 存储大小限制为 2mb+,取决于浏览器也会有所不同。
222+
- 它们不会过期。
223+
- 数据绑定在同一来源下(域名/端口/协议)。
228224

229225
| `localStorage` | `sessionStorage` |
230226
|----------------|------------------|
231-
| Shared between all tabs and windows with the same origin | Visible within a browser tab, including iframes from the same origin |
232-
| Survives browser restart | Survives page refresh (but not tab close) |
227+
| 在同源的所有标签页和窗口之间共享 | 在浏览器标签中可见,包括来自同一来源的iframe |
228+
| 浏览器重启后数据仍然保留 | 页面刷新后数据仍然保留(不包括标签页关闭) |
233229

234-
API:
230+
API
235231

236-
- `setItem(key, value)` -- store key/value pair.
237-
- `getItem(key)` -- get the value by key.
238-
- `removeItem(key)` -- remove the key with its value.
239-
- `clear()` -- delete everything.
240-
- `key(index)` -- get the key number `index`.
241-
- `length` -- the number of stored items.
242-
- Use `Object.keys` to get all keys.
243-
- We access keys as object properties, in that case `storage` event isn't triggered.
232+
- `setItem(key, value)` -- 存储键值对。
233+
- `getItem(key)` -- 根据键名获取相应的值。
234+
- `removeItem(key)` -- 删除该键对应的键值对。
235+
- `clear()` -- 清空存储。
236+
- `key(index)` -- 获取该索引下的键名。
237+
- `length` -- 存储对象的长度。
238+
- 使用 `Object.keys` 获取所有的键。
239+
- 假如我们使用对象属性的形式来访问键,则 `storage` 事件不会被触发。
244240

245-
Storage event:
241+
Storage 事件:
246242

247-
- Triggers on `setItem`, `removeItem`, `clear` calls.
248-
- Contains all the data about the operation, the document `url` and the storage object.
249-
- Triggers on all `window` objects that have access to the storage except the one that generated it (within a tab for `sessionStorage`, globally for `localStorage`).
243+
- 在调用 `setItem``removeItem``clear`方法后触发。
244+
- 包含有关操作,文档 `url` 和存储对象的所有数据。
245+
- 在除当前触发了事件的对象以外所有能访问到存储对象的 `window` 对象上都会被触发(在 `sessionStorage` 有效范围的同一标签页下,在 `localStorage` 的有效范围下)。

0 commit comments

Comments
 (0)