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. My console says the error is in the "if" statement, but I don't understand why. Any thoughts?
CodePudding user response:
Try using
if ( localStorage.getItem('fruits') !== null) {
fruits = JSON.parse(localStorage.getItem('fruits'));
}
CodePudding user response:
I believe the answer lies in the quotes. JSON syntax is very strict and requires the use of double quotes. Change out all your single quotes in your if statement to double quotes and see if that fixes your issue.