gpt4 book ai didi

javascript - 修改 JavaScript 中的排序函数

转载 作者:行者123 更新时间:2023-11-30 08:41:55 24 4
gpt4 key购买 nike

谁能解释一下下面的代码:

var values = [213, 16, 2058, 54, 10, 1965, 57, 9];
values.sort(function(value1,value2){ return value2 - value1; });

我无法理解 value1 和 value2 是如何从数组值中加载的,以及它如何反转排序结果。

最佳答案

排序函数执行以下操作:

return value2 - value1;

让我们让它更详细一点,这样我们就可以看到发生了什么:

var values = [213, 16, 2058, 54, 10, 1965, 57, 9];
values.sort(function(value1,value2){
console.log(value2 + ' - ' + value1 + ' = ' + (value2 - value1) + ' | (' + (value2 - value1 > 0 ? 'positive | ' + value2 + ' should be before ' + value1 : 'negative | ' + value2 + ' should be after ' + value1) + ')');

return value2 - value1;
});

输出:

  16 -  213 = -197 | (negative | 16 should be after 213)
2058 - 16 = 2042 | (positive | 2058 should be before 16)
2058 - 213 = 1845 | (positive | 2058 should be before 213)
54 - 16 = 38 | (positive | 54 should be before 16)
54 - 213 = -159 | (negative | 54 should be after 213)
10 - 16 = -6 | (negative | 10 should be after 16)
1965 - 10 = 1955 | (positive | 1965 should be before 10)
1965 - 16 = 1949 | (positive | 1965 should be before 16)
1965 - 54 = 1911 | (positive | 1965 should be before 54)
1965 - 213 = 1752 | (positive | 1965 should be before 213)
1965 - 2058 = -93 | (negative | 1965 should be after 2058)
57 - 10 = 47 | (positive | 57 should be before 10)
57 - 16 = 41 | (positive | 57 should be before 16)
57 - 54 = 3 | (positive | 57 should be before 54)
57 - 213 = -156 | (negative | 57 should be after 213)
9 - 10 = -1 | (negative | 9 should be after 10)

如果对所有值执行以下操作,您会注意到如果 value2 大于 value1,结果将始终为正,并且会向前移动在数组中 - 基本上以反向排序的数组结束。

关于javascript - 修改 JavaScript 中的排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25521107/

24 4 0
文章推荐: javascript - 使用 JQuery for 循环创建
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com