在测试特定用例后减少没有初始值的空数组
Reduce of empty array with no initial value after testing a specific use case
变量 min
将包含给定数组中 4 个最小项的总和。
变量 max
将包含给定数组中 4 个最大项的总和。
JS:
function main() {
const arr = [1, 2, 3, 4, 5]
const min = arr.sort().filter((element, index, array) => element !== array[array.length - 1]).reduce((accumulator, currentValue) => {
return accumulator + currentValue
})
const max = arr.sort().filter((element, index, array) => element !== array[0]).reduce((accumulator, currentValue) => {
return accumulator + currentValue
})
console.log(min, max)
}
main()
正如预期的那样,[1,2,3,4,5]
将得到 10、14。但是,如果给定的数组是 [5,5,5,5,5]
,程序将 return TypeError: Reduce of empty array with no initial value
.
这是为什么?
谢谢。
当所有元素都相同时,
条件 element !== array[array.length - 1]
对所有元素都为假,因为所有元素都与最后一个元素相同。
因此 filter(...)
的结果将是一个空数组,
所以你得到了你得到的错误。
事实上这个实现是有缺陷的。
最好使用 index
而不是元素值:
function main(arr) {
const count = 4;
const sorted = arr.sort((a, b) => a - b);
const sum = (accumulator, currentValue) => accumulator + currentValue;
const min = sorted
.filter((element, index) => index < count)
.reduce(sum);
const max = sorted
.filter((element, index) => index >= arr.length - count)
.reduce(sum);
console.log(min, max);
}
main([1, 2, 3, 4, 5]);
main([5, 5, 5, 5, 5]);
我还进行了其他一些改进:
- 将数组作为函数的参数,以便于测试
- 不要对数组排序两次,一次就够了
- 正如 @Andrew 在评论中指出的那样,
arr.sort()
没有对整数进行正确排序,您需要将其传递给比较器函数才能获得预期效果
- 减少重复逻辑:提取
sum
函数和count
变量
- 用内联 lambda 表达式替换代码块
变量 min
将包含给定数组中 4 个最小项的总和。
变量 max
将包含给定数组中 4 个最大项的总和。
JS:
function main() {
const arr = [1, 2, 3, 4, 5]
const min = arr.sort().filter((element, index, array) => element !== array[array.length - 1]).reduce((accumulator, currentValue) => {
return accumulator + currentValue
})
const max = arr.sort().filter((element, index, array) => element !== array[0]).reduce((accumulator, currentValue) => {
return accumulator + currentValue
})
console.log(min, max)
}
main()
正如预期的那样,[1,2,3,4,5]
将得到 10、14。但是,如果给定的数组是 [5,5,5,5,5]
,程序将 return TypeError: Reduce of empty array with no initial value
.
这是为什么?
谢谢。
当所有元素都相同时,
条件 element !== array[array.length - 1]
对所有元素都为假,因为所有元素都与最后一个元素相同。
因此 filter(...)
的结果将是一个空数组,
所以你得到了你得到的错误。
事实上这个实现是有缺陷的。
最好使用 index
而不是元素值:
function main(arr) {
const count = 4;
const sorted = arr.sort((a, b) => a - b);
const sum = (accumulator, currentValue) => accumulator + currentValue;
const min = sorted
.filter((element, index) => index < count)
.reduce(sum);
const max = sorted
.filter((element, index) => index >= arr.length - count)
.reduce(sum);
console.log(min, max);
}
main([1, 2, 3, 4, 5]);
main([5, 5, 5, 5, 5]);
我还进行了其他一些改进:
- 将数组作为函数的参数,以便于测试
- 不要对数组排序两次,一次就够了
- 正如 @Andrew 在评论中指出的那样,
arr.sort()
没有对整数进行正确排序,您需要将其传递给比较器函数才能获得预期效果 - 减少重复逻辑:提取
sum
函数和count
变量 - 用内联 lambda 表达式替换代码块