首页 > 解决方案 > 异常没有抛出我的字符串——它抛出的是文字异常而不是我的抛出

问题描述

我正在练习 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);
   }

标签: javascript

解决方案


您需要在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);
   }


推荐阅读