다음 함수가 (코드의 세 번째 섹션에서) 숫자로 문자열을 정렬하는 이유를 이해하는 데 문제가 있습니다.자바 스크립트 .sort 매개 변수 이해
var myArray = [10, 44, 32, 100, 0, 44, 3, 4];
console.log(myArray.toString()); // 10, 44, 32, 100, 0, 44, 3, 4 --> unsorted
myArray.sort();
console.log(myArray.toString()); // 0,10,100,3,32,4,44,44 --> sorted like strings
// this is what confuses me:
myArray.sort(function (a, b) {
return a - b;
});
console.log(myArray.toString()); // 0,3,4,10,32,44,44,100 --> sorted numerically
특히 :
방법은
a
및b
채워합니까?a - b
숫자를 숫자 순서로 정렬하는 이유는 무엇입니까?함수가 한 번에 2 개의 숫자 만 검사하는 경우 모든 숫자를 적절한 순서로 정렬하려면 어떻게합니까? (즉
a
및b
)
의 중복 가능성 [정말로 자바 스크립트 분류에서 일어나는] (http://stackoverflow.com/questions/8588921/what-really-happens-in-javascript-sort) –