简体   繁体   中英

how does sort comparison get it's arguments from the array

I'm reading JavaScript For Web Developer 3rd Edition and I am stuck how this works. I understand how the compare function works. But values.sort(compare); confuses me. compare looks at 2 arguments and compares them. But I do not pass 2 arguments. Even if I did pass 2 arguments to the function, how does it compare itself to the rest of the items in the Array? Does the sort function do something in the background that I don't know about? If so, how does it work? Thank you in advance :)

 function compare(value1, value2) { if (value1 < value2) { return 1; } else if (value1 > value2) { return -1; } else { return 0; } } var values = [0, 1, 5, 10, 15]; values.sort(compare); alert(values); //15,10,5,1,0 

The compare function is a call back function that you supply to the sort function. The sort function will use some algorithm to sort the list. When the sort function's algorithm needs to compare two items from the list, the sort method will call the compare function with the two items.

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