线上购物车addToCart函数console.log输出异常求助
addToCart Function Hey there! Let's break down what's going on here. The error message you're seeing tells the whole story: your test expects the addToCart function to return the string like 'ice cream has been added to your cart.', but right now your function is returning the entire cart array instead.
Your template literal is actually totally correct—${item} has been added to your cart. produces the right message, and your console.log is working as intended. The problem lies in the last line of your function: you're returning cart instead of the message string the test is looking for.
Here's the Fix:
Modify the return statement to send back the message instead of the cart array. If you still need to keep track of the cart (which you probably do), store the message in a variable first so you can both log it and return it:
function addToCart(item) { var price = Math.floor(Math.random() * 100) + 1; var obj = {itemName: item, itemPrice: price}; cart.push(obj); const cartMessage = `${item} has been added to your cart.`; console.log(cartMessage); return cartMessage; // Return the message, not the cart array }
Why This Works:
- Your cart still gets updated correctly (you're still pushing the new item object into
cart), so all your existing cart logic stays intact. - The function now returns the exact string the test is expecting, which will resolve the
Expected [{...}] to equal '...'error.
If for some reason the test was supposed to check the console.log output instead of the function's return value, you'd need to adjust how the test asserts against logged messages—but based on the error you shared, the issue is definitely a return value mismatch.
内容的提问来源于stack exchange,提问作者Jayd Robinson

