localStorage.getItem读取[1,2,3]
时间: 2024-01-04 18:02:38 浏览: 25
如果你使用 localStorage.setItem 存储了一个数组 [1,2,3],那么使用 localStorage.getItem 读取时会返回一个字符串 "[1,2,3]",而不是一个数组。如果你希望读取到一个数组,需要使用 JSON.parse() 方法将字符串转换成数组,示例代码如下:
```javascript
const arrStr = localStorage.getItem('myArray');
const arr = JSON.parse(arrStr);
console.log(arr); // [1, 2, 3]
```
相关问题
localStorage.getItem读取['1', '2', '3']
如果你使用 localStorage.setItem 存储了一个字符串数组 ['1', '2', '3'],那么使用 localStorage.getItem 读取时会返回一个字符串 "[\"1\",\"2\",\"3\"]",而不是一个数组。如果你希望读取到一个字符串数组,需要使用 JSON.parse() 方法将字符串转换成数组,示例代码如下:
```javascript
const arrStr = localStorage.getItem('myArray');
const arr = JSON.parse(arrStr);
console.log(arr); // ['1', '2', '3']
```
需要注意的是,如果存储的是数字数组 [1, 2, 3],则读取时返回的是一个数字数组,而不是一个字符串数组。
window.localStorage.getItem
`window.localStorage.getItem()` 是 JavaScript 中用于获取本地存储中特定键的值的函数。
用法:
```
window.localStorage.getItem(key);
```
其中,key 是要获取的键的名称。如果该键不存在,则返回 null。
例如:
```
//设置值
localStorage.setItem("name", "John");
//读取值
var name = localStorage.getItem("name");
```
如果你想读取所有的键值,可以使用localStorage.key(index)来遍历所有的键值
```
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
console.log( localStorage.getItem( localStorage.key( i ) ) );
}
```