简体   繁体   中英

Can someone help me understand how compare function is involved for sorting purpose here?

 var arr=[2,4,1,8,5]; var result=arr.sort(function compare(a,b) { return ba; }); document.writeln(result);

This is the example given to understand usage of JavaScript Array sort() method on javatpoint.com

in a simple word

sort function replace index based on return value

like

[1 5 3]

is (5 > 3) true so it is correct and goto next

(ba) = 5-3 return a positive value [true]

(ba) = 3-5 return a Negative value [false] it is not correct and must replaced with previous index

then sort function will do this in While loop until there is no negative value and return Array

In this case there was no need to use compare function. This function is useful when you want to compare objects which can not be compared by JavaScript using any operator or inbuilt functions.

You can find more details here - https://www.w3schools.com/js/js_array_sort.asp

Now the role of compare function here is that it compares two values - in this case numbers - and returns a number (0 means both numbers are equal, positive or negative number indicate greater than or less than relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM