[英]Sum without highest and lowest number
I've been spending a few hours trying to understand where the error is in this code.我已经花了几个小时试图了解此代码中的错误所在。 Debugging indicated that the output is 0 as it should be for any number less than 0. However, this code is still unable to pass the test:调试表明输出为 0,因为它应该是任何小于 0 的数字。但是,此代码仍然无法通过测试:
function sumArray(array)
{
return array < 1 || array == null ? 0
:array.reduce((a, b) => a + b) - Math.max(...array) - Math.min(...array);
}
console.log(sumArray([-3]))
function sumValues (array) {
if (array != null && array.length > 0) {
let min = Math.min(...array); // lowest in array by spreading
let max = Math.max(...array); // highest in array by spreading
// Sum up the numbers in the array
let sum = array.reduce((acc, val) => acc + val, 0);
// Do the math
let result = sum - max - min;
if (result > 0) {
return result
} else {
return 0
}
} else {
return 0
}
}
console.log(sumValues([1,2,3,4,5,6]))
Definitely better:绝对更好:
function sumArray(array) {
if (array == null || array.length <= 1) {
return 0
}
var max = Math.max(...array);
var min = Math.min(...array);
var sum = 0
for (i = 0; i < array.length; i++) {
sum += array[i];
}
return sum - max - min
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.