I'm still in the early stages of learning Javascript, having dabbled with it for a couple of weeks. This marks my first time posting, so I apologize if my explanation is not comprehensive enough, but I'll do my best!
My goal is to create a function called VendingMachine(snack, cash) that contains a list of 4 items along with their respective prices, taking two arguments: "snack name" (snack) and the amount of "cash inserted" (cash). I've experimented with both objects and arrays to store the list, finding some success with arrays, but I believe objects are the way to go because...
When using an array with nested arrays for the snack list, the issue arises when the 'for()' loop fails to find the matching value for "snack", resulting in 'undefined' output instead of displaying "Sorry, try again."
By storing the item list in the machine as an object, my aim is to verify that "snack === object.KEY" and that "cash >= VALUE" corresponding to that KEY. However, my struggle lies in lacking familiarity with object syntax, making it challenging for me to grasp explanations provided by others or apply them to my specific situation. The only thing that didn't work out was:
for(var key in objects) {
var value = objects[key];
}
// Utilizing an array
function vendingMachine(snack, cash) {
//declaring nested arrays for snacks & costs
var snacks = [
["Espresso", 1],
["Cappuccino", 2.50],
["Chocolate bar", 2],
["Potato Chips", 3.50]
]
//looping through the array to match snack and check funds
for (var i = 0; i < snacks.length; i++) {
if (snack === snacks[i][0] && cash >= snacks[i][1]) {
if (snack === "Potato Chips") {
console.log("Your " + snack + " have been served");
} else {
console.log("Your " + snack + " has been served");
}
}
else if (snack === snacks[i][0] && cash <= snacks[i][1]) {
console.log("Insufficient funds. Please insert more cash.");
}
}
}
// Utilizing an object (still a work-in-progress or possibly extremely incorrect, seeking clarification!)
function vendingMachine(snack, cash) {
//declaring nested arrays for snacks & costs
var snacks = {
"Espresso": 1,
"Cappuccino": 2.50,
"Chocolate bar": 2,
"Potato Chips": 3.50
}
if (snack === snacks.hasOwnProperty() && cash >= snacks.key) {
if (snack === "Potato Chips") {
console.log("Your " + snack + " have been served");
} else {
console.log("Your " + snack + " has been served");
}
}
else if (snack === snacks.hasOwnProperty() && cash <= snacks.key) {
console.log("Insufficient funds. Please insert more cash.");
}
else if (snack != snacks.hasOwnProperty()) {
console.log(snack + " does not exist. Please try again.") //returns undefined
}
}