You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用localStorage实现购物车:数组仅存最后一个元素的问题求助

Fix: localStorage Only Saves the Last Cart Item

Hey there! I see the issue with your code—let's break it down and fix it quickly.

The Problem

Every time your code runs, you're creating a brand new empty array with let names = []. That means you're not retaining any of the previous items you added; you just push the current item into this fresh array and overwrite the localStorage entry. No wonder only the last item sticks around!

The Solution

You need to first fetch the existing array from localStorage (if there is one), add your new item to that array, then save the updated array back. Here's how to adjust your code:

// Step 1: Get existing items from localStorage, or start with an empty array
let names = JSON.parse(localStorage.getItem('name')) || [];

// Step 2: Add your new item to the array
numPlass++;
var set = cart_item.childNodes[numPlass].innerHTML;
names.push(set);

// Step 3: Save the updated array back to localStorage
localStorage.setItem('name', JSON.stringify(names));

Key Notes

  • The JSON.parse(localStorage.getItem('name')) || [] part is crucial: if there's nothing stored under the 'name' key (like on first load), getItem returns null, and the || [] ensures we start with an empty array instead of throwing an error.
  • A quick heads-up: childNodes includes text nodes (like spaces or line breaks in your HTML), so you might accidentally grab empty content. If you only want actual element nodes, try using cart_item.children[numPlass] instead.
  • To debug, add console.log(names) after pushing the item—this will show you the full array in your browser's dev tools, so you can confirm multiple items are being added correctly.

内容的提问来源于stack exchange,提问作者שאול שאולי

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:49:19