This code is very confusing, namely because you're passing an array into the method instead of giving the method proper parameters. You can first improve your code by adding parameters to the method:
function priceCalc(town, product, qty) {
There we go, this is much cleaner. Next, onto the issue you're having. For the second argument (
product
) you're passing in the
string `coffee`
. What this means is when you call
product[index]
you're getting a
character at that index in the string, which clearly isn't what you want. Ultimately, there's two ways you can accomplish what you're after. First is to declare the products
outside of the function, and then pass the arrays into the method like so:
const coffee = [0.5, 0.4, 0.45]
const water = [0.8, 0.7, 0.7]
const beer = [1.2, 1.15, 1.1]
const sweets = [1.45, 1.3, 1.35]
const peanuts = [1.6, 1.5, 1.55]
function priceCalc(town, product, qty) {
..
price = product[index];
console.log(price);
}
priceCalc('Sofia', coffee, 4);
The alternative, if you've truly got your heart set on actually passing in the
string version, is to instead create an object with the product names, and then reference that object:
function priceCalc(town, product, qty) {
const products = {
'coffee': [0.5, 0.4, 0.45],
'water': [0.8, 0.7, 0.7],
'beer': [1.2, 1.15, 1.1],
'sweets': [1.45, 1.3, 1.35],
'peanuts': [1.6, 1.5, 1.55]
};
..
price = products[product][index];
console.log(price);
}
priceCalc('Sofia', 'coffee', 4);
What the above is doing is taking that
string coffee and then looking up the associated array in the
products
object with the same product name. Then, we access the index of the array to get the price value.