异常不会抛出我的字符串,而是抛出文字异常而不是我的抛出

时间:2020-04-16 18:31:30

标签: javascript

我正在尝试使用try / catch。为什么没有空数组异常“没有输入分数”的输出?相反,它吐出的是“ average = 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);
   }

1 个答案:

答案 0 :(得分:1)

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

相关问题