forEach() Introduction
ForEach() method requires a callback function (this function is created by us but not called by us) as a parameter
Pass three parameters in the callback function:
- The first parameter is the element currently traversing
- The second parameter is the index of the element currently traversing
- The third parameter is the array being traversed
Example code:
let myArr = ['Wang Yi', 'Wang Er', 'Wang San']; ((item, index, arr) => { ('item:' + item); ('index:' + index); ('arr:' + (arr)); });
Print result:
item: Wang Yi
index:0
arr:["King One","King Two","King Three"]
----------
item: Wang Er
index:1
arr:["King One","King Two","King Three"]
----------
item: Wang San
index:2
arr:["King One","King Two","King Three"]
----------
Note: forEach() has no return value. It can also be understood as: the return value of forEach() is undefined
Right nowlet tempArry = ()
There is no point in receiving this way
Can forEach() change the original array?
Can forEach() change the original array? Most people will get it wrong about this issue. Let's take a look at the following code
1. The elements of the array are basic data types: (The original array cannot be changed)
let numArr = [1, 2, 3]; ((item) => { item = item * 2; }); (numArr); // Print results:[1, 2, 3]
You have to read the above code carefully, the print result is[1, 2, 3]
,no[2, 4, 6]
2. The elements of the array are reference data types: (When modifying the entire element object directly, the original array cannot be changed)
let objArr = [ { name: 'Yunmu', age: 20 }, { name: 'Xu Song', age: 30 }, ]; ((item) => { item = { name: 'G.E.M.', age: '29', }; }); ((objArr)); // Print results:[{"name": "Yunmu","age": 20},{"name": "Xu Song","age": 30}]
3. The elements of the array are reference data types: (When modifying a certain attribute in the element object, you can change the original array)
let objArr = [ { name: 'Yunmu', age: 28 }, { name: 'Xu Song', age: 30 }, ]; ((item) => { = 'G.E.M.'; }); ((objArr)); // Print results:[{"name":"G.E.M.","age":28},{"name":"G.E.M.","age":30}]
So in fact, forEach will not directly change the object that calls it, but that object may be changed by the callback function. If you understand that the above phenomenon is value transfer, and the reference data type assignment is a transfer of the reference address, it is actually easy to understand.
My B station has also published a video about the difference between basic data and referenced data types. If you don't know this basis, please make sure to make up for it.
If you need to modify the original array through forEach, it is recommended to use parameters 2 and 3 in forEach. For details, please see the following standard practices
forEach() Modify the original array through parameters 2 and parameters 3: (Standard practice)
// 1. The elements of the array are basic data typeslet numArr = [1, 2, 3]; ((item, index, arr) => { arr[index] = arr[index] * 2; }); ((numArr)); // Print result: [2, 4, 6] // 2. When the elements of the array are referenced data types, directly modify the objectlet objArr = [ { name: 'Yunmu', age: 28 }, { name: 'Xu Song', age: 34 }, ]; ((item, index, arr) => { arr[index] = { name: 'Xiao Ming', age: '10', }; }); ((objArr)); // Print result: [{"name":"Xiao Ming","age":"10"},{"name":"Xiao Ming","age":"10"}] // 3. When the element of the array is a reference data type, modify a certain property of the object.let objArr2 = [ { name: 'Yunmu', age: 28 }, { name: 'Xu Song', age: 34 }, ]; ((item, index, arr) => { arr[index].name = 'Xiao Ming'; }); ((objArr2)); // Print results:[{"name":"Xiao Ming","age":28},{"name":"Xiao Ming","age":34}]
Summarize:
If it is just traversing the array, you can use the forEach() method
However, if you want to change the content of the elements in the array while iterating through the array, then it is best to use the map() method. The map() method itself will return a completely new array after processing. Do not use the forEach() method to avoid some low-level errors
sort() Introduction
sort()
: Sort the elements of the array from small to large (the original array will be changed)
If you do not have parameters when using the sort() method,
The default sorting order is to convert elements into strings according toUnicode encoding, sort from small to large
Example 1: (When the element in the array is a string)
let arr1 = ['e', 'b', 'd', 'a', 'f', 'c']; let result = (); // Sort array arr1 ('arr1 =' + (arr1)); ('result =' + (result));
Print result:
arr1 =["a","b","c","d","e","f"]
result =["a","b","c","d","e","f"]
From the print result above, we can see that the sort method will change the original array, and the return value of the method is the same result.
Example 2: (When the element in the array is a number)
let arr2 = [5, 2, 11, 3, 4, 1]; let result = (); // Sort array arr2 ('arr2 =' + (arr2)); ('result =' + (result));
Print result:
arr2 = [1,11,2,3,4,5]
result = [1,11,2,3,4,5]
In the print result above, you will find that after sorting using sort(), the number 11 is actually in front of the number 2. Why is this? Because it was mentioned abovesort()
The method is to followUnicode encodingSort by.
So what if I want the numbers in arr2 to be sorted completely from small to large? Keep reading.
sort() method: Customize the sorting rules when using parameters
If we have parameters in the sort() method, we canCustomizeSorting rules. The specific methods are as follows:
We can add a callback function in sort() to specify the sort rules.
Two formal parameters need to be defined in the callback function, and the browser will use the elements in the array as real parameters to call the callback function.
The browser determines the sort of elements based on the return value of the callback function: (Important)
- if
compareFunction(a, b)
If less than 0, then a will be arranged before b;- if
compareFunction(a, b)
equal to 0 , the relative positions of a and b remain unchanged- if
compareFunction(a, b)
greater than 0, b will be arranged before aIf you just look at the above text, it may not be easy to understand. Let's take a look at the following examples and you will definitely understand
let arr = [5, 2, 11, 3, 4, 1]; (function (a, b) { ("a:" + a, "b:" + b); }); /* a:2 b:5 a:11 b:2 a:3 b:11 a:4 b:3 a:1 b:4 */
For example: sort the numbers in the array from small to large
Writing method 1:
let arr = [5, 2, 11, 3, 4, 1]; // Custom sorting ruleslet result = (function (a, b) { if (a > b) { // If a is greater than b, then b is arranged before a return 1; } else if (a < b) { // If a is less than b, then a is arranged before b return -1; } else { // If a is equal to b, the position remains unchanged return 0; } }); ('arr =' + (arr)); ('result =' + (result));
Print result:
arr = [1, 2, 3, 4, 5, 11];
result = [1, 2, 3, 4, 5, 11];
The above code is too long-winded, and it can actually be simplified to the following writing method:
Writing method 2:
let arr = [5, 2, 11, 3, 4, 1]; // Custom sorting ruleslet result = (function (a, b) { return a - b; // Ascending order // return b - a; // Order in descending order}); ('arr =' + (arr)); ('result =' + (result));
The print result remains unchanged.
The above code can also be written in the form of ES6, that is, change the function to an arrow function, and the writing method is as follows
Writing method 3: (arrow function)
let arr = [5, 2, 11, 3, 4, 1]; // Custom sorting ruleslet result = ((a, b) => { return a - b; // Ascending order}); ('arr =' + (arr)); ('result =' + (result));
The above code, because there is only one sentence in the function body, you can remove the return statement and continue to simplify it to the following writing method
Writing method 4:(recommend)
let arr = [5, 2, 11, 3, 4, 1]; // Custom sorting rules: ascending orderlet result = ((a, b) => a - b); ('arr =' + (arr)); ('result =' + (result));
Among the various writing methods above, writing method 4 is the one we use most in actual combat development.
In order to ensure the concise and elegant code, in the following code, whenever functions are involved, we will try to use the arrow function in ES6 to write it as much as possible.
Example of sort method: sort the array from small to large according to a field inside
This example is very common to sort arrays from small to large. But in actual development, there will always be some tricks.
The following code is often used in actual development and must be mastered. The complete code is as follows:
let dataList = [ { title: "Brand shoes, high quality and low price", publishTime: 200, }, { title: "Not very expensive, but very warm", publishTime: 100, }, { title: "Eat with me for food", publishTime: 300, }, ]; ("Array before sorting:" + (dataList)); // Sort the dataList array from small to large according to the publishTime field. (It will change the original array) ((a, b) => parseInt() - parseInt()); ("Sorted array:" + (dataList));
Print result:
Array before sorting:[
{"title":"Brand shoes, high quality and low price purchase","publishTime":200},
{"title":"Not very expensive, but very warm","publishTime":100},
{"title":"Food food with me","publishTime":300}
]Sort array:[
{"title":"Not very expensive, but very warm","publishTime":100},
{"title":"Brand shoes, high quality and low price purchase","publishTime":200},
{"title":"Food food with me","publishTime":300}
]
In the above code, someone may ask: The publishTime field is already of nuber type, why do you need to do a parseInt() conversion before sorting?
This is because this kind of data is generally returned to the front end by the backend interface. The data may be of number or string type, so it is safer to do parseInt() conversion first. This is a good working habit.
In fact, it is best to use const first when defining above, which can ensure more safety of the program. Please use let when variables are needed.
Finally, I would like to say that in the prototype of the array, such as forEach, map, filter, some, every, find, and findIndex, the methods on the array prototype can not only accept the first callback function, but also accept the second value to specify this value in the previous callback function (very rarely used), but you should also note that if the callback function uses the arrow function, it cannot bind this, because the arrow function does not have this, and it is always taken from this in the upper scope (the interview is often taken, and the arrow function does not have arguments, but the remaining parameters can be used... solved).
Summarize
This is the article about the classic scenes of forEach modifying the original array and sort sort in Js. This is the end. For more related Js forEach modifying the original array, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!