[英]Average Calculator for an Array (null arguments returns NaN)
Uses rest parameter and for...of loop for an array...对数组使用 rest 参数和 for...of 循环...
function average(...nums) { let total = 0; for(const num of nums) { total += num; } let avr = total / arguments.length; return avr; } console.log(average(2, 6)); console.log(average(2, 3, 3, 5, 7, 10)); console.log(average(7, 1432, 12, 13, 100)); // returns NaN - required to return 0. console.log(average());
Problem: for no arguments - console.log(average());
问题:没有 arguments - console.log(average());
- Returns NaN where the correct answer must be 0. - 返回正确答案必须为 0 的 NaN。
Any good shorthand solution here?这里有什么好的速记解决方案吗?
Modify the function as -将 function 修改为 -
function average(...nums) {
if(nums.length === 0){
return 0;
}
let total = 0;
for(const num of nums) {
total += num;
}
let avr = total / arguments.length;
return avr;
}
You could just check arguments.length at the start of the function.您可以在 function 的开头检查 arguments.length。 Something like:就像是:
function average(...nums) {
//check if no args are passed & return 0
if(arguments.length === 0) return 0;
//else
let total = 0;
for(const num of nums) {
total += num;
}
let avr = total / arguments.length;
return avr;
}
It's not very elegant but...它不是很优雅,但...
const average = (...arr) => arr.reduce( ( acc, current ) => acc + current, 0 ) / (arr.length || 1); console.log(average(2, 6)); console.log(average(2, 3, 3, 5, 7, 10)); console.log(average(7, 1432, 12, 13, 100)); console.log(average());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.