javascript - 异常没有抛出我的字符串——它抛出的是文字异常而不是我的抛出
问题描述
我正在练习 try/catch。为什么空数组异常的输出不是“未输入分数”?相反,它吐出“平均= NaN”。一如既往地感谢您的帮助!
输出:
平均 = 84.75
平均 = 76
分数不能小于 0
平均值 = NaN
只能输入整数。
// Returns the average of the numbers in the scores array.
function findAverage(scores) {
var sum = 0;
for (var score of scores){
if(score < 0){
throw "Scores cannot be less than 0";
}
}
if (scores === []){
throw "No scores were entered.";
}
for (score of scores){
if (Number.isInteger(score)===false){
throw "Only integers can be entered.";
}
}
scores.forEach(function(score) {
sum += score;
});
return sum / scores.length;
}
console.log("Average = " + findAverage([90, 85, 71, 93]));
console.log("Average = " + findAverage([76]));
try{
console.log("Average = " + findAverage([90, -85, 71, 93])); // Should not accept negative numbers
}
catch(exception){
console.log(exception);
}
try{
console.log("Average = " + findAverage([])); // Should not accept empty arrays
}
catch(exception) {
console.log(exception);
}
try{
console.log("Average = " + findAverage([60, "cat", 70])); // Should not accept non-numbers
}
catch(exception){
console.log(exception);
}
解决方案
您需要在if
语句中进行以下更改。检查它是否是一个数组并检查长度以确保它不为0。
// Returns the average of the numbers in the scores array.
function findAverage(scores) {
var sum = 0;
for (var score of scores){
if(score < 0){
throw "Scores cannot be less than 0";
}
}
if (!Array.isArray(scores) || scores.length === 0){
throw "No scores were entered.";
}
for (score of scores){
if (Number.isInteger(score)===false){
throw "Only integers can be entered.";
}
}
scores.forEach(function(score) {
sum += score;
});
return sum / scores.length;
}
console.log("Average = " + findAverage([90, 85, 71, 93]));
console.log("Average = " + findAverage([76]));
try{
console.log("Average = " + findAverage([90, -85, 71, 93])); // Should not accept negative numbers
}
catch(exception){
console.log(exception);
}
try{
console.log("Average = " + findAverage([])); // Should not accept empty arrays
}
catch(exception) {
console.log(exception);
}
try{
console.log("Average = " + findAverage([60, "cat", 70])); // Should not accept non-numbers
}
catch(exception){
console.log(exception);
}
推荐阅读
- javascript - 这将打开正确的提示,但是当我按 Enter 时没有任何反应
- python-3.x - Python 3.7 和 Dataflow - SSL 证书问题
- python-3.x - 服务器仅打印来自最近连接的客户端的消息
- javascript - 在 Safari 上下载 base64 pdf
- javascript - PassportJS nodejs 请求 https
- mysql - MySQL 大表分片到基于唯一 ID 的小表
- java - 从 java 代码运行 Linux 命令(远程操作系统)
- docker - couchdb docker image:如何预填充数据库
- r - 使用 dplyr 进行分组和转置
- java - Class.getCanonicalName 有性能问题吗?