Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

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

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 work, but my question is why?! I would really like to understand this piece of code properly.

The site, W3 Schools says:

You can fix this by providing a function that returns -1, 0, or 1:

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a,b){return a-b});

Why would only -1, 0 or 1 be returned? I have Googled, and return can return pretty much any value you want.

Again, if this is an incredibly dumb question I apologise.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The sort callback has to return

  • a negative number if a < b
  • 0 if a === b
  • a positive number if a > b

Three possible return values are needed because the sort function needs to know whether a is smaller than, equal to, or larger than b in order to correctly position a in the result array.

It is very common to just return -1, 0 and 1 if you working with non-numerical data (I guess that's why W3Schools mentions it). But if you use numerical data, you can simply subtract the values because

  • if a < b then a - b < 0, i.e. a negative number
  • if a === b then a - b === 0, i.e. 0
  • if a > b then a - b > 0, i.e. a positive number

W3Schools is not very precise which is one of the reason why you should avoid it. Use MDN instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...