如何使用JavaScript修改localStorage中对象的属性值
How to Update a Property of an Object Stored in localStorage
Got it, let's walk through exactly how to modify the name property of your ship object in localStorage. The key thing to remember here is that localStorage only stores string values—so we have to convert between JSON strings and JavaScript objects to make changes.
Here's the step-by-step breakdown:
- Pull the stored data from localStorage using the key "ship"
- Convert the JSON string back to a JavaScript object (since we stored it with
JSON.stringify()earlier) - Update the
nameproperty on the object - Turn the updated object back into a JSON string
- Save the new string back to localStorage using the same key
Working Code Example
// 1. Get the stored JSON string const storedShip = localStorage.getItem("ship"); // Add a check to avoid errors if the key doesn't exist if (storedShip) { // 2. Parse the string into a usable object let ship = JSON.parse(storedShip); // 3. Update the name property to your new value ship.name = "The New Black Pearl"; // Replace with your desired name // 4. Convert back to JSON string & 5. Save it back to localStorage localStorage.setItem("ship", JSON.stringify(ship)); }
Why Your Original Attempt Didn't Work
Your line localStorage.setItem(localStorage.getItem("ship").name, "newName"); has two main issues:
localStorage.getItem("ship")returns a string, not an object—so you can't directly access.nameon it. You need to parse it first to get the object.- The first argument to
setItem()should be the key name ("ship"), not the value of thenameproperty. Your code was trying to create a new localStorage entry with the old ship name as the key, which isn't what you want.
Adding the if (storedShip) check is a good habit—it prevents JSON.parse() from throwing an error if the "ship" key doesn't exist in localStorage yet.
内容的提问来源于stack exchange,提问作者Ning
相关产品推荐
相关产品推荐

