From 0bcd5e669ee240213d6851c42b0f6ef17068903c Mon Sep 17 00:00:00 2001 From: zhaijinglang Date: Sun, 28 Jun 2026 20:29:57 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E5=B0=86javascript=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=8D=95=E4=BE=8B=E6=A8=A1=E5=BC=8F=E8=B4=AD=E7=89=A9?= =?UTF-8?q?=E8=BD=A6=E6=95=B0=E6=8D=AE=E7=BB=93=E6=9E=84=E6=94=B9=E4=B8=BA?= =?UTF-8?q?Map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...15\225\344\276\213\346\250\241\345\274\217.md" | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git "a/DesignPattern/1-\345\215\225\344\276\213\346\250\241\345\274\217.md" "b/DesignPattern/1-\345\215\225\344\276\213\346\250\241\345\274\217.md" index 3d643ac..cd0f9bd 100644 --- "a/DesignPattern/1-\345\215\225\344\276\213\346\250\241\345\274\217.md" +++ "b/DesignPattern/1-\345\215\225\344\276\213\346\250\241\345\274\217.md" @@ -506,7 +506,7 @@ const PRIVATE_KEY = Symbol(); class ShoppingCartManagerJS { static #instance; - #products = []; + #products = new Map(); constructor(key) { if (key !== PRIVATE_KEY) { @@ -522,15 +522,20 @@ class ShoppingCartManagerJS { } add(name, quantity) { - this.#products.push({ name, quantity }); + if(this.#products.has(name)){ + this.#products.set(name, this.#products.get(name) + quantity); + return; + }else{ + this.#products.set(name, quantity); + } } viewCart() { - if (this.#products.length === 0) { + if (this.#products.size === 0) { return; } - this.#products.forEach((product) => { - console.log(`${product.name} ${product.quantity}`); + this.#products.forEach((quantity, name) => { + console.log(`${name} ${quantity}`); }); } }