En JavaScript: tengo un operador ternario al que se le indica que devuelva un porcentaje de propina del 15% si el monto de la factura está entre $ 50-300; de lo contrario, se le indica que devuelva un porcentaje de propina del 20%. En un monto de factura de $275, todavía rinde %20. He visto muchos ejemplos de operadores ternarios que funcionan y mi código parece estar redactado correctamente y, sin embargo, el resultado siempre es incorrecto. ¿De qué manera estoy fallando?
const bill_1 = 40; const bill_2 = 275; const bill_3 = 430; let bill; let tip_percentage = bill >= 50 && bill <= 300 ? 0.15 : 0.2; bill = bill_1; console.log(`The first table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`); bill = bill_2; console.log(`The second table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`); bill = bill_3; console.log(`The third table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);Como dijo @Matt en el comentario, tip_percentage no es una función y debe calcularse cada vez que cambia el monto de la factura.
Prueba esto:
const bill_1 = 40; const bill_2 = 275; const bill_3 = 430; function getTip(bill) { var tip = (bill >= 50 && bill <= 300) ? 0.15 : 0.2; return tip; } alert(`Bill one's tip: ${getTip(bill_1)}`); alert(`Bill two's tip: ${getTip(bill_2)}`); alert(`Bill two's tip: ${getTip(bill_3)}`);tip_percentage ya está calculado.
Si desea hacer diferentes valores de resultado dependiendo de la variable, hágalos en forma de funciones.
const bill_1 = 40; const bill_2 = 275; const bill_3 = 430; const tip_percentage = (bill) => (bill >= 50 && bill <= 300 ? 0.15 : 0.2); const printTipResult = (bill) => { console.log(`The third table's bill came out to $${bill}. After the tip of ${tip_percentage(bill)}% (equalling: $${bill * tip_percentage(bill)}) was added, the final amount owed is: $${bill * tip_percentage(bill) + bill}`); }; printTipResult(bill_1); printTipResult(bill_2); printTipResult(bill_3);