【发布时间】:2021-06-25 09:29:30
【问题描述】:
我正在尝试从角度对象数组中获取数据:
我的代码结构:
storegeArray: any [];
-
填写数组“-”中的所有字段:
this.storegeArray = new Array(100).fill("-"); -
将数据推送到特定id的数组中:
this.storegeArray[data.vehicle_id] = {x: location[1], y: location[0]}; -
在本地存储中保存数组(storegeArray):
localStorage.setItem("coordinates",this.storegeArray);
到这里一切正常。'
console.log(this.storegeArray)
输出:
(100) ["-", "-", "-", {…}, "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-"]
0: "-"
1: "-"
2: "-"
3: {x: 33.8953628, y: 35.4906471}
4: "-"
5: "-"
6: "-"
7: "-"
8: "-"
.......
工作正常,我在 id = 3 id of data.vehicle_id 中有数据
在全局情况下,我在数组中的不同索引中有多个数据,所以我使用这种方法来获取:
const myArrayFromLocalStorage = localStorage.getItem('coordinates');
if (myArrayFromLocalStorage) {
for(let i=0; i<myArrayFromLocalStorage.length; i++){
if(JSON.stringify(myArrayFromLocalStorage[i] != "-")){
console.log(JSON.stringify(myArrayFromLocalStorage[i]));
}
}
}
输出:
"-"
","
"-"
","
"-"
","
"["
"o"
"b"
"j"
"e"
"c"
"t"
" "
"O"
"b"
"j"
"e"
"c"
"t"
"]"
","
"-"
","
"-"
","
"-"
我尝试做的是在数组中获取以查看数据(对象)而不是“-”并获取表示获取 x 和 y 的数据(对象)。
我做错了什么?
【问题讨论】:
-
使用这个: const myArrayFromLocalStorage = JSON.parse(localStorage.getItem('coordinates');)
-
我收到此错误:ERROR SyntaxError: Unexpected token , in JSON at position 1 at JSON.parse (
) @TusharShahi -
@lampardbre 只需清除您的 localStorage,因为它现在充满了非 json 格式(由以前的错误实现引起)。此外,如果 localStorage 中还没有数据,
getItem将返回 null,因此JSON.parse将失败,请在我的回答的第 4 步中查看如何安全地进行操作
标签: javascript arrays angular