帮助我试图让我的代码警报最大的数字输入和最低为什么我不这样做?
let price;
let items = 0;
let sum=0;
let big = 0 ;
let small = 0;
price = Number(prompt("Please enter the price of the Item you choose to buy or enter -1 to stop: "));
while (price != -1){
sum=sum+price;
items++;
avg = sum/items;
Big = Math.max(Number(price));
small = Math.min(Number(price));
price = Number(prompt("Please enter the price of the Item you choose to buy or enter -1 to stop: "));
}
alert("You have purchased "+items+" items!");
alert("the sum of items you purchased is: $"+sum);
alert("the Averege of the items is: " + avg);
alert("The highest item price purchased was: "+ Big);
alert("The lowest item price was: "+ small);
使用函数isNumeric检查valid numbers
。使用名为itemsPurchased
的数组存储所有有效的购买not including empty string, negative numbers
.
使用template strings, destructuring assignment, Array.prototype.reduce() , Math.max(), spread operator , Math.min() and Array.prototype.length
得到期望的结果。
function isValidNumber(str) {
if (typeof str != "string") return false;
return (
!isNaN(str) &&
!isNaN(parseFloat(str))
);
}
function purchaseCalculation() {
let price,
expensive,
cheap,
itemsNumber,
average,
total,
itemsPurchased = [];
price = prompt(
"Please enter the price of the Item you choose to buy or enter -1 to stop: "
);
while (price !== "-1") {
if (isValidNumber(price) && Number(price) >= 0) {
itemsPurchased.push(Number(price));
}
price = prompt(
"Please enter the price of the Item you choose to buy or enter -1 to stop: "
);
}
expensive = itemsPurchased.length === 0 ? 0 : Math.max(...itemsPurchased);
cheap = itemsPurchased.length === 0 ? 0 : Math.min(...itemsPurchased);
total = itemsPurchased.reduce((total, item) => total + item, 0);
itemsNumber = itemsPurchased.length;
average = total === 0 ? 0 : total / itemsNumber;
return [cheap, expensive, total, itemsNumber, average];
}
const [cheap, expensive, total, itemsNumber, average] = purchaseCalculation();
alert(
`You have purchased ${itemsNumber} ${itemsNumber > 1 ? "items" : "item"}!`
);
alert(
`The sum of ${
itemsNumber > 1 ? "items" : "item"
} you purchased was: $${total}`
);
alert(
`The average of the ${itemsNumber > 1 ? "items" : "item"} was: ${average}`
);
alert(`The highest item price purchased was: ${expensive}`);
alert(`The lowest item price was: ${cheap}`);