简体   繁体   English

为什么我的 stringify 不能在“if”语句中解析?

[英]Why won't my stringify parse in an "if" statement?

const friends = ["john","peter","bob"];
localStorage.setItem("friends", JSON.stringify(friends));

const values = JSON.parse(localStorage.getItem("friends"));
console.log(values[2]);
// console.log(values[1]);
// console.log(values[2]);

let fruits;
console.log(fruits);

if (localStorage.getItem('fruits')) {
 fruits = JSON.parse(localStorage.getItem('fruits'));
}
else {
 fruits = [];
}

console.log(fruits);
fruits.push("apple");
fruits.push("orange");
localStorage.setItem("fruits", JSON.stringify(fruits));

Why will the first array behave properly in chrome where I can clearly check the console and application from dev.tools but when I try to make an empty array and push different values fx "apple" and "orange" I can't.为什么第一个数组在 chrome 中表现正常,我可以从 dev.tools 清楚地检查控制台和应用程序,但是当我尝试创建一个空数组并推送不同的值 fx“apple”和“orange”时,我做不到。 My console says the error is in the "if" statement, but I don't understand why.我的控制台说错误在“if”语句中,但我不明白为什么。 Any thoughts?有什么想法吗?

I believe the answer lies in the quotes.我相信答案就在引号中。 JSON syntax is very strict and requires the use of double quotes. JSON 语法非常严格,需要使用双引号。 Change out all your single quotes in your if statement to double quotes and see if that fixes your issue.将 if 语句中的所有单引号更改为双引号,看看是否能解决您的问题。

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

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