Why does points.sort(function(a, b){return a-b}); return -1, 0 or 1?

前端 未结 6 1718
滥情空心
滥情空心 2020-12-08 23:47

My difficulty here could be my mathematical illiteracy, but I was trying to sort some numbers in a JavaScript array and this is the solution I found online. It does indeed w

6条回答
  •  没有蜡笔的小新
    2020-12-09 00:36

    If Function(a, b) is less than 0, sort a to an index lower than b, i.e. a comes first.

    If Function(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.

    Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

    If Function(a, b) is greater than 0, sort b to an index lower than a, i.e. b comes first. Function(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

提交回复
热议问题