gpt4 book ai didi

Javascript .sort() 函数 : what are return 0, 返回 -1 并返回 1?

转载 作者:行者123 更新时间:2023-11-30 14:45:23 27 4
gpt4 key购买 nike

我正在学习 Javascript,目前正在学习数组的 .sort() 函数。我知道它可以不带参数,也可以在 a-b 和 b-a 之间带一个参数。

不过,我不明白的是return 0return -1return 1 的用法。这是一个示例(来源:http://www.codewars.com/kata/572df796914b5ba27c000c90):

var arr=[1,2,3,4,5,6,100,999]
arr.sort((a,b)=>{
if (a%2==b%2) return a-b;
if (a%2>b%2) return -1;
return 1;
})
console.log(arr)

//output: [ 1, 3, 5, 999, 2, 4, 6, 100 ]

我明白它应该做什么,即分开奇数和偶数并按升序对它们进行排序。但是return -1return 1是什么意思呢?有人可以逐步指导我完成此功能吗?

我试着玩弄代码并更改一些值,例如将 return -1 更改为 return 0,试图了解它是如何工作的,但我还是不明白。

我在哪里可以找到有关 return 元素的详细信息?

最佳答案

根据 sort docs :

If the parameter functionComparison is supplied, the elements of the array are sorted according to the return value of the comparison function. If a and bare two elements to compare, then:

If functionComparison(a, b) is less than 0, we sort a with an index less than b( a will be ranked before b)

If functionComparison(a, b) returns 0, we leave a and b unchanged relative to each other, but sorted with respect to all the other elements. Note: The ECMAScript standard does not guarantee this behavior, so all browsers (eg Mozilla versions prior to 2003) do not respect this. If functionComparison(a, b) is greater than 0, we sort b with an index less than a.

functionComparison(a, b) must always return the same result from the same pair of arguments. If the function returns inconsistent results, then the order in which the items are sorted is not defined.

现在如果a > b , returning 1a positive value是一回事,类似地,如果 a < b然后返回 -1difference是一样的。如果both are equal difference is 0因此 return 0

关于Javascript .sort() 函数 : what are return 0, 返回 -1 并返回 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49005027/

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