You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

线上购物车addToCart函数console.log输出异常求助

Fixing the Return Value Mismatch in Your 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:31:25