This code tries to perform a currency converter, and returns a NaN every time the result is displayed in the alert... however, to try to solve the problem:
So far it was possible to try but I am almost sure that the problem is there, that the objects inside the array are being accessed incorrectly and that is what you want to know.
do {
const currencies = [{result: 0},
{dolar: 129},
{euro: 132},
{franco: 133},
{real: 23},
{yuan: 19}];
pesos = prompt("Enter pesos to convert");
currency = prompt("Enter a currency");
function divide (pesos, currency) {
if (pesos > 0 && currency == "dolar") {
currencies.result = pesos / currencies.dolar;
alert(pesos + " pesos are $" + currencies.result.toFixed(2) + " dolars");
exit = prompt("to continue press ENTER | if you want to exit type EXIT");
return
}
if (pesos > 0 && currency == "euro") {
currencies.result = pesos / currencies.euro;
alert(pesos + " pesos are €" + currencies.result.toFixed(2) + " euros");
exit = prompt("to continue press ENTER | if you want to exit type EXIT");
return
}
if (pesos > 0 && currency == "franco") {
currencies.result = pesos / currencies.franco;
alert(pesos + " pesos are " + currencies.result.toFixed(2) + " francos");
exit = prompt("to continue press ENTER | if you want to exit type EXIT");
return
}
if (pesos > 0 && currency == "real") {
currencies.result = pesos / currencies.real;
alert(pesos + " pesos are " + currencies.result.toFixed(2) + " reales");
exit = prompt("to continue press ENTER | if you want to exit type EXIT");
return
}
if (pesos > 0 && currency == "yuan") {
currencies.result = pesos / currencies.yuan;
alert(pesos + " pesos are " + currencies.result.toFixed(2) + " yuanes");
exit = prompt("to continue press ENTER | if you want to exit type EXIT");
return
}
else {
alert("You must enter a value and a currency");
}
}
divide(pesos, currency)
} while (exit != "EXIT");
You need to have all currencies and result in a single object, not in an array of objects.
For smaller code, without repetition, you could add in the object the currency sign and name for plurals (not implemented).
function divide(pesos, currency) {
if (!(currency in currencies) || !pesos || pesos < 0) {
alert("You must enter a value and a currency");
return;
}
currencies.result = pesos / currencies[currency];
alert(pesos + " pesos are " + currencies.result.toFixed(2) + " " + currency + "s");
return prompt("to continue press ENTER | if you want to exit type EXIT");
}
const currencies = {
result: 0,
dolar: 129,
euro: 132,
franco: 133,
real: 23,
yuan: 19,
};
let pesos, currency;
do {
pesos = +prompt("Enter pesos to convert"),
currency = prompt("Enter a currency");
} while (divide(pesos, currency) != "EXIT");