0

I am having a little trouble with this assignment for school. I am using JavaScript to make a menu and give the total price of that order. I am doing 4 menus: Breakfast, Lunch, Dinner, each with sides (Trying to get a little extra credit). I am supposed to use prompt() for this assignment. I was able to get the numbers in an array but I can't get them to equal out anything. I have posted the code I have, but if there is a simpler version I will gladly be doing that too.

I have the menu in HTML and the code itself for the javascript is in the <script> tag.

const b1 = 4;
const b2 = 5;
const bs1 = 2;

const l1 = 10;
const l2 = 20;
const l3 = 5;


const d1 = 10;
const d2 = 20;
const s1 = 2;
const s2 = 3;
const s3 = 5


function orderHere() {
  var i = 0;
  var order;
  sum = 0

  for (i = 0; i < 2; i++) {
    order = prompt("What would you like to eat today?", "Order Here" + (i + 1));
    sum += order;

  }

  alert("Your price is $" + sum + ". Enjoy your meal!");
}
orderHere();
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Devious
  • 11
  • 2
  • What are they typing in the prompt? – epascarello Nov 28 '22 at 19:26
  • I made you a snippet and execute the script by adding `orderHere();` to the end – mplungjan Nov 28 '22 at 19:28
  • I have a feeling it is a dupe of https://stackoverflow.com/questions/1664282/how-can-i-refer-to-a-variable-using-a-string-containing-its-name – epascarello Nov 28 '22 at 19:28
  • 1
    @epascarello A dupe but a horrific dupe. Please do not point ppl to answers using `eval` or `window[variable]` – mplungjan Nov 28 '22 at 19:30
  • [Here is what you actually need](https://stackoverflow.com/questions/37515959/how-to-create-an-associative-array-in-javascript-literal-notation) an object that has the food as key and the price as value – mplungjan Nov 28 '22 at 19:32

2 Answers2

1

There is room for improvement but you're off to a good start. To calculate the sum you'll want to put your menu items in a map, which for JavaScript is just an object (there is the built in Map data type but for this assignment the object is fine).

const menu = { b1: 4, b2: 5, ... }

Then when you get a response you can look up the menu item to get it's price and add it's price to the sum.

sum += menu[order]

Just beware that you should never trust user input so be sure to check that the menu item actually exists before trying to add it to the sum.

Stephen Gilboy
  • 5,572
  • 2
  • 30
  • 36
0

You could look into javascript maps.

For example:

const prices = new Map();

prices.set("dinner 1", 10);
//The first parameter is the food
//the second is the price

console.log(prices.get("dinner 1")); //returns 10