首页 > 解决方案 > Trying to follow a numerical array sort steps in Javascript

问题描述

I'm learning to do an array sort in Javascript on an array of numbers, I've looked at the mdn page and done a search, this is the sort I'm trying to understand:

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

// [1, 2, 3, 4, 5]

I understand what's happening, I just can't seem to find an easy to follow step by step article on the javascript array sort which shows how 'a' and 'b' are being compared and moved around, for instance once the end of the array is reached does the sort repeat itself until all items are sorted? I guess I'm curious about the implementation in a simple to understand way.

To add, I've tried console logging the output but still was a bit confused by the way it was done so looking for a more concrete answer from someone who knows.

标签: javascriptarrayssorting

解决方案


功能的实现与sort浏览器相关

例如 WebKit 实现:https ://gist.github.com/964673


推荐阅读