简体   繁体   中英

What is the reason JSON.parse() acts differently?

I can not determine the difference between these two approaches:

let gigi;
if(localStorage.getItem('gigi')){
    gigi = JSON.parse(localStorage.getItem('gigi'))
}else{
    gigi=[]
}
console.log(gigi);

While the code above shows empty array, the below one shows up null. Why?

let aa=[]
let che =JSON.parse(localStorage.getItem('aa'))
console.log(che);

getItem will return the value null if no value exists at that key in storage.

In the first code, this branch:

if(localStorage.getItem('gigi')){

excludes that possibility. In the second code, you're not doing any such test, you're passing it into JSON.parse regardless. JSON.parse(null) will coerce the null into a string, and will then parse 'null' into the value null .

If you want to do this concisely, you can do

const gigi = JSON.parse(localStorage.getItem('aa') ?? '[]')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM