【发布时间】:2018-02-25 19:06:36
【问题描述】:
我正在尝试使用 JS 制作购物车,我的任务之一是创建 placeOrder 函数。
placeOrder() 函数接受一个参数,即信用卡号。
如果没有收到参数,该函数应打印出对不起,我们没有为您存档的信用卡。
如果收到卡号,该函数应打印出
Your total cost is $71, which will be charged to the card 83296759。然后,它应该清空购物车数组。
但是,当我将总函数调用到字符串中时,会一直返回 undefined。
var cart = [];
function getCart() {
return cart;
}
function setCart(c) {
cart = c;
return cart;
}
function addToCart(itemName) {
var object = {
[itemName]: Math.floor(Math.random(1, 100) * 100)
};
cart.push(object);
console.log(`${itemName} has been added to your cart`);
return cart;
}
function total() {
if (cart.length !== 0) {
var totalValue = [];
for (var i = 0; i < cart.length; i++) {
for (var item in cart[i]) {
totalValue.push(cart[i][item]);
var sum = totalValue.reduce(function(a, b) {
return a + b;
}, 0);
console.log(`The total value is ${sum}`);
}
}
} else {
return ("Your shopping cart is empty.")
}
}
function placeOrder(cardNumber) {
if (cardNumber === undefined) {
return ("Sorry, we don't have a credit card on file for you.");
} else {
console.log(`Your total cost is $${total()}, which will be charged to the card ${cardNumber}`);
cart = [];
return cart;
}
}
addToCart("a");
addToCart("be");
addToCart("cart");
placeOrder(14564);
输出:
Your total cost is $undefined, which will be charged to the card 14564
【问题讨论】:
-
请删除所有不必要的代码
-
如果购物车不为空,您的函数不会返回任何内容。
console.log≠return。应尽量少用console.log,调试时除外。 -
@SlavaKnyazev 没有,我添加了所有我调用的。
-
@Carcigenicate 我的错,我会改写问题,但是,我尝试使用 return 并得到相同的输出
-
@Rookie 只需从
total返回sum。我不确定你尝试了什么,但这会奏效。
标签: javascript arrays oop