[英]What is the reason JSON.parse() acts differently?
我無法確定這兩種方法之間的區別:
let gigi;
if(localStorage.getItem('gigi')){
gigi = JSON.parse(localStorage.getItem('gigi'))
}else{
gigi=[]
}
console.log(gigi);
雖然上面的代碼顯示了空數組,但下面的代碼顯示了 null。 為什么?
let aa=[]
let che =JSON.parse(localStorage.getItem('aa'))
console.log(che);
如果存儲中該鍵不存在值, getItem
將返回值null
。
在第一個代碼中,這個分支:
if(localStorage.getItem('gigi')){
排除了這種可能性。 在第二個代碼中,您沒有進行任何此類測試,而是將其傳遞給JSON.parse
無論如何。 JSON.parse(null)
會將null
強制轉換為字符串,然后將'null'
解析為值null
。
如果你想簡潔地做到這一點,你可以這樣做
const gigi = JSON.parse(localStorage.getItem('aa') ?? '[]')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.