简体   繁体   English

JSON.parse() 行为不同的原因是什么?

[英]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.虽然上面的代码显示了空数组,但下面的代码显示了 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.如果存储中该键不存在值, getItem将返回值null

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无论如何。 JSON.parse(null) will coerce the null into a string, and will then parse 'null' into the value null . JSON.parse(null)会将null强制转换为字符串,然后将'null'解析为值null

If you want to do this concisely, you can do如果你想简洁地做到这一点,你可以这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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