简体   繁体   中英

Understanding a Javascript Codewars challenge

     var gimme = function (inputArray) {
     var order = inputArray.slice().sort(function(a,b) { return a-b;});
    return inputArray.indexOf(order[1]);
     };

This is a function to find the index number of the middle number in a sequence, when given a triplet of numbers. However I don't understand the section:

     (function(a,b) { return a-b;});

Could someone explain the purpose of this part? I would be very grateful. Thanks!

This is an example from MDN :

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
    return a - b;
});
console.log(numbers);

The result is [1, 2, 3, 4, 5];

So this is a very simple comparator for integers.


Comparators works like the following:

  • if a < b, return a negative
  • if b < a, return a positive
  • in other cases, return zero

This function uses a simple mathematical property of integers.

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