Angular 13 应用中出现 "Argument expression expected" 错误的原因是什么?

What causes the "Argument expression expected" error in this Angular 13 app?

我正在开发一个电子商务应用程序,它的前端是在 Angular 13.

中制作的

下面的代码旨在计算购物车中商品的价格

import { Component, OnInit } from '@angular/core';

@Component({
  selector: '.app-top-cart',
  templateUrl: './top-cart.component.html',
  styleUrls: ['./top-cart.component.css']
})
export class TopCartComponent implements OnInit {
  cartItems: any = [
    {
      id: 1,
      title: "iPhone 9",
      description: "An apple mobile which is nothing like apple",
      price: 549,
      discountPercentage: 12.96,
      rating: 4.69,
      stock: 94,
      brand: "Apple",
      category: "smartphones",
      thumbnail: "https://dummyjson.com/image/i/products/1/thumbnail.jpg",
      images: [
        "https://dummyjson.com/image/i/products/1/1.jpg",
        "https://dummyjson.com/image/i/products/1/2.jpg",
      ]
    },
    {
      id: 2,
      title: "iPhone X",
      description: "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...",
      price: 899,
      discountPercentage: 17.94,
      rating: 4.44,
      stock: 34,
      brand: "Apple",
      category: "smartphones",
      thumbnail: "https://dummyjson.com/image/i/products/2/thumbnail.jpg",
      images: [
        "https://dummyjson.com/image/i/products/2/1.jpg",
        "https://dummyjson.com/image/i/products/2/2.jpg",
      ]
    }
  ];

  constructor() { }

  totalPrice: number = 0;

  doTotalPrice(){
    let total = 0,
    this.cartItems.forEach((item: { price: number, quantity: number; }) => {
      total += item.price * item.quantity
    }),
    this.totalPrice = total,
 }

  ngOnInit(): void {
    this.doTotalPrice();
  }

}

问题

以上代码无法编译。它在第 54 行给出错误 Argument expression expected,其中 doTotalPrice 方法关闭。

我的错误在哪里?

doTotalPrice(){
    let total = 0,
    this.cartItems.forEach((item: { price: number, quantity: number; }) => {
      total += item.price * item.quantity
    },
    this.totalPrice = total,
 }

你没有关闭你的函数,你使用逗号而不是分号。

doTotalPrice(){
    let total = 0,
    this.cartItems.forEach((item: { price: number, quantity: number; }) => {
      total += item.price * item.quantity
    });
    this.totalPrice = total;
 }

奖金,更清晰的代码:

this.totalPrice = this.cartItems.reduce(
  (p, { price, quantity }) => p + price * quantity, 
  0
);

您必须删除 forEach() 后面的逗号;

 yourArray.forEach(element=>{
 //do something 
 });