我想創建一個陣列,其中包含來自我的購物網站購物車的本地存盤物件的每個產品 ID。問題是我為每個產品的 id 生成一個陣列而不是一個包含所有產品 id 的陣列的函式
var cartStorage = JSON.parse(localStorage.getItem("cart"));
cartStorage.forEach(function (cart, index) {
let cartIds = [cart._id];
console.log(cartIds); // logs one array for each id instead of just one array with every id's
});
我已經嘗試了幾個小時,但似乎沒有任何效果,我猜我必須使用 forEach() 但我不能讓它作業?
uj5u.com熱心網友回復:
您正在回圈let cartIds 內定義。它在每個回圈中被創建和重新創建。所以,當然,它只包含一個元素。在回圈外定義它,并在回圈中將內容推入其中。
const cartStorage = JSON.parse(localStorage.getItem("cart"));
let cartIds = [];
cartStorage.forEach(cart => cartIds.push(cart._id));
console.log(cartIds);
甚至更好:
const cartStorage = JSON.parse(localStorage.getItem("cart"));
const cartIds = cartStorage.map(cart => cart._id);
console.log(cartIds);
另請注意,如果您的 localStorage 中沒有“購物車”,getItem將回傳null,并且您的代碼將崩潰。你需要處理這個案子。
uj5u.com熱心網友回復:
在回圈外創建變數,并將值推送到此陣列中。
var cartIds = []
var cartStorage = JSON.parse(localStorage.getItem("cart"));
cartStorage.forEach(function (cart, index) {
cartIds.push(cart._id)
});
console.log(cartIds) // this has all the pushed values inside
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386043.html
下一篇:影像加載在反應中無法正常作業
