函数在调用string后返回undefined

时间:2018-02-25 19:06:36

标签: javascript arrays oop

我试图使用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);
&#13;
&#13;
&#13;

输出:

Your total cost is $undefined, which will be charged to the card 14564

2 个答案:

答案 0 :(得分:0)

您希望确保total始终返回number,例如:

&#13;
&#13;
var cart = [{
    "a": 86
  },
  {
    "be": 2
  },
  {
    "cart": 24
  }
];

function total(cart) {
  return cart
    .reduce(function(prices, item) {
      return prices.concat(Object.keys(item).map(k => item[k]));
    }, [])
    .reduce(function(sum, price) {
      return sum += price;
    }, 0);
}

console.log(total([]));
console.log(total(cart));
&#13;
&#13;
&#13;

placeOrder中的用法可能如下所示:

&#13;
&#13;
function total(cart) {
  return cart
    .reduce(function(prices, item) {
      return prices.concat(Object.keys(item).map(k => item[k]));
    }, [])
    .reduce(function(sum, price) {
      return sum += price;
    }, 0);
}

function placeOrder(cardNumber, cart) {
  if (cardNumber === undefined) {
    return "Sorry, we don't have a credit card on file for you.";
  }

  if (cart.length === 0) {
    return "You cart is empty";
  }

  return `Your total cost is $${total(cart)}, which will be charged to the card ${cardNumber}`;
  return [];
}

console.log(placeOrder(1234, []));
console.log(placeOrder(1234, [{
  a: 1
}, {
  b: 2
}]));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

  • 我不知道该阵列的目的是什么totalValue,但您不需要该功能reduce,只需循环项目并总结金额。
  • 您循环浏览每件商品的价值,直接使用Object.values(cart[i]).pop();获取商品金额。
var sum = 0;
for (var i = 0; i < cart.length; i++) {
  var amount = Object.values(cart[i]).pop();
  sum += amount;        
}

最后,返回sum

&#13;
&#13;
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 sum = 0;
    for (var i = 0; i < cart.length; i++) {
      for (var item in cart[i]) {
        sum += cart[i][item];        
      }
    }
    console.log(`The total value is ${sum}`);
    
    return sum;
  }
  
  return -1; // Could be 0, this is up to you.
}

function placeOrder(cardNumber) {
  if (cardNumber === undefined) {
    return ("Sorry, we don't have a credit card on file for you.");
  } else {
  
    var sum = total();
    if (sum) {
    console.log(`Your total cost is $${sum}, which will be charged to the card ${cardNumber}`);
    } else {
      console.log("Your shopping cart is empty.")
    }
    cart = [];
    return cart;
  }
}

addToCart("a");
addToCart("be");
addToCart("cart");
placeOrder(14564);
&#13;
&#13;
&#13;