javascript 中的购物车数据聚合

Cart data aggregation in javascript

我需要为我的购物车编写一个数据聚合方法,但我卡住了。我有空数组和循环的 const 有效负载,它将 运行 getData() 方法用于我购物车中的每个产品,并将结果推送到我的空数组。我还需要我的 getData() 方法,它将 return 用于我的 id、数量、价格和 priceSingel。我们在 CarProduct 构造函数中获得的所有这些。我还是新手,有时我确实会被基础知识卡住。

const payload = {
        products: [],
        address: 'test',
        totalPrice: thisCart.totalPrice,
      };

      for(let product of thisCart.products) {
        product.getData();
      }
      payload.products.push(product);
  /* get data for .getData */
    getData() {
      return id;
      return amount;
      return price;
      return priceSingle;
      return params;
    }
/* part of cart product constructor */
class CartProduct {
    constructor (menuProduct, element) {
      const thisCartProduct = this;

      thisCartProduct.id = menuProduct.id;
      thisCartProduct.name = menuProduct.name;
      thisCartProduct.price = menuProduct.price;
      thisCartProduct.priceSingle =menuProduct.priceSingle;
      thisCartProduct.amount = menuProduct.amount;

很难帮助您了解您的代码。

但是,您可以解决一些问题:

一个方法不能有多个有效return,第一个遇到的就用。 所以对于你的getData(),你应该return一个对象:

getData() {
  return { // this is a shortcut where key is named like the variable
    id,
    amount,
    price,
    priceSingle,
    params
  }
}

我不知道你的 params 是什么。

其次,在循环时向数组添加数据,而不是在循环之后(此处您不使用 getData() return)

for(let product of thisCart.products) {
  payload.products.push(product.getData());
}