Ionic Native Storage存储对象数组后调用splice报错求助
问题分析与解决方案
看起来你遇到的核心问题是存储的数据结构和检索时的操作不匹配,加上JSON序列化时的用法错误,导致了splice报错和JSON解析异常。咱们一步步拆解:
1. 为什么splice会报错?
你存储的时候,把数组包装在了一个对象里:
this.nativeStorage.setItem('array1', { property: array1 })
这意味着NativeStorage中保存的是一个带有property属性的对象,而不是直接的数组。但检索时,你直接把返回的结果当成数组来调用splice:
array2 = array1.splice(0,5);
这里的array1其实是那个包装对象,而对象并没有splice方法——这就是报错的根源。
2. JSON序列化的错误原因
你尝试用JSON序列化解决类型问题,但用法错了:
- 存储时你把数组转成字符串存在
property里:{ property: JSON.stringify(array1)} - 但检索时直接对整个对象
array1执行JSON.parse(array1),而array1是一个JavaScript对象,不是JSON字符串,所以会抛出Unexpected token o的语法错误(因为对象转字符串是[object Object],解析时第一个字符是o,不符合JSON格式)。
正确的解决方案
根据你的需求,有几种可行的修正方式:
方式一:直接存储数组(推荐)
如果不需要额外包装,直接把数组存入NativeStorage:
// 存储 this.nativeStorage.setItem('array1', array1) .then(() => console.log('array1 stored'), error => console.log('array1 not stored', error)); // 检索 this.nativeStorage.getItem('array1').then(storedData => { const array1 = storedData as CertainType[]; array2 = array1.splice(0,5); // 现在array1是真正的数组,可以正常调用splice }, error => console.error('Error getting array', error));
方式二:保留包装对象的存储结构
如果你必须用{ property: array1 }的结构存储,检索时要先提取出property对应的数组:
// 存储代码不变 this.nativeStorage.setItem('array1', { property: array1 }) .then(() => console.log('array1 stored'), error => console.log('array1 not stored', error)); // 检索时先取property属性 this.nativeStorage.getItem('array1').then(storedObj => { const array1 = storedObj.property as CertainType[]; array2 = array1.splice(0,5); }, error => console.error('Error getting array', error));
方式三:正确使用JSON序列化(解决类型疑虑)
如果担心存储后的类型丢失,正确的序列化方式是:
- 存储时序列化整个要保存的数据(数组或包装对象)
- 检索时先解析成对象/数组,再操作
比如序列化包装对象:
// 存储 this.nativeStorage.setItem('array1', JSON.stringify({ property: array1 })) .then(() => console.log('array1 stored'), error => console.log('array1 not stored', error)); // 检索 this.nativeStorage.getItem('array1').then(storedStr => { const storedObj = JSON.parse(storedStr); const array1 = storedObj.property as CertainType[]; array2 = array1.splice(0,5); }, error => console.error('Error getting array', error));
或者直接序列化数组:
// 存储 this.nativeStorage.setItem('array1', JSON.stringify(array1)) .then(() => console.log('array1 stored'), error => console.log('array1 not stored', error)); // 检索 this.nativeStorage.getItem('array1').then(storedStr => { const array1 = JSON.parse(storedStr) as CertainType[]; array2 = array1.splice(0,5); }, error => console.error('Error getting array', error));
内容的提问来源于stack exchange,提问作者Rafael de Castro
相关产品推荐
相关产品推荐

