Article Directory
Preface
When I used the sort method for the first time, I found that the arrays were not sorted in order of size. I checked the manual and found that if you want to sort according to other standards, you need to provide a comparison function. What are the parameters a and b in this function?
After referring to everyone's notes, I summarized some things that I don't understand. If there are errors, I hope everyone can comment and make progress together!
1. Definition and usage
1) Basic instructions
- Definition: The sort() method is used to sort the elements of an array.
- Syntax: arrayObject.sort(sortby)
sortby: optional. Specifies the sort order. Must be a function.
- Return value: The array is sorted on the original array without generating a copy.
2) Use without parameters
If no parameters are used when calling this method, the elements in the array will be sorted in alphabetical order. To be more precise, they will be sorted in the order of character encoding .
var a=[1,4,2,12,453,22]
a.sort();
console.log('数组a:')
console.log(a)
Output:
2. Parameters a, b
1) a is num[1]; b is num[0]!
To provide a comparison function, we must first know who a and b are?
I always think that a is num[0] and b is num[1]. I can't understand everyone's comparison function. I have been inverted! ! !
The code wants you to look at two points: ①a is num[1]; b is num[0] ②If the function returns a negative value, exchange a and b
var num=[1,4,2,12,453,22];
num.sort((a,b)=>{
console.log('a='+a+'b='+b)
return -1;//返回负值,则交换a与b
})
console.log(num)
Output:
You can push this simple exchange process: return -1 directly, and keep swapping a and b
2) Examples
Example 1: Realize sorting from small to large
The code is as follows (example):
var num=[1,1,12,453,22];
num.sort((a,b)=>{
console.log('a='+a+'b='+b)
return a-b;//a=b或a>b,返回0或正值,不做改变;a<b,返回负值,说明后面的数小于前面的数,调换位置
})
console.log(num)
Output:
Example 2: Arrange the array into the smallest number
Input an array of non-negative integers, concatenate all the numbers in the array into one number, and print the smallest one of all the numbers that can be spliced
var minNumber = function(nums) {
nums.sort((a,b)=>{
if(''+a+b<''+b+a){
return -1;}
else return 1;
});
return nums.join("")
};
Output:
3) The realization principle of sort function
Still learning, learn to sort that pile of things and come back to fill the pit, come on! ! !
to sum up
Understand who the a and b parameters are, and the positive or negative return value represents the exchange or not, you can already use the sort function!