gpt4 book ai didi

javascript - 在测试特定用例后减少没有初始值的空数组

转载 作者:行者123 更新时间:2023-11-29 19:00:20 24 4
gpt4 key购买 nike

变量 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],程序将返回TypeError: Reduce of empty array with no initial value

这是为什么?

谢谢。

最佳答案

当所有元素都相同时,条件 element !== array[array.length - 1] 对所有元素都为 false,因为所有元素都与最后一个元素相同。因此 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 表达式替换代码块

关于javascript - 在测试特定用例后减少没有初始值的空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47253976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com