簡體   English   中英

循環對象 javascript

[英]looping over objects javascript

所以最近我學會了使用 for in 循環來循環對象。 我們得到了這個問題來解決一個基本的購物車 object,其中包含 object 的名稱,然后是數量和價格。

const cart = {
  "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 },
  "Pink Bucket Hat": { quantity: 2, priceInCents: 1260 },
};

我們必須編寫 2 個函數,一個以美分計算庫存總成本,另一個顯示庫存。

  1. calculateCartTotal function 將放入購物車並返回其中所有物品的總價格(以美分為單位)。
  2. printCartInventory function 將接收購物車並返回一個字符串,由 \n 連接,其中包含每個項目的數量和名稱。

我能夠輕松完成第一個問題,但在第二個問題上掙扎。

第一個 function:

function calculateCartTotal(cart) {
  let total = 0;
  for(let item in cart){
    const product = cart[item]
    const quantity = product.quantity
    const price = product.priceInCents
    total += quantity * price
  }
  return total
}

第二個 function:

function printCartInventory(cart) {
  let inventory = ""
  for(let item in cart){
    const product = cart[item]
    const quantity = product.quantity
    inventory += `${quantity}x${product}/n`
  }
  return inventory
}

當我測試第二個 function 時,自動分級機給出了這個錯誤:

expected '2x[object Object]/n1x[object Object]/n1x[object Object]/n3x[object Object]/n' to include '2xCanvas Tote Bag\n1xBlack and White Chuck On Dress\n1xNatural Straw Wide Brim Hat\n3xBlue Stripe Casual Shirt'

查看錯誤消息時,請注意顯示[object Object]的部分。 這是您的代碼 output 的一部分,應該響鈴。 這意味着您的代碼嘗試將 object 放在字符串中,而不是字符串中。

有罪的代碼在這里:

inventory += `${quantity}x${product}/n`

product不是字符串,而是 object。 這不是你想要的 output 那里。 您想要 output 是產品的名稱,它是,而不是與該鍵關聯的值。 所以應該是:

inventory += `${quantity}x${item}/n`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM