1. Preface
forEach and map are two methods of arrays, and they are used to iterate over arrays. It is often used in the processing data of vue projects. Here are some examples of the differences and specific usage of the two.
2. Code
1. Similarities
- All are array methods
- All are used to traverse arrays
- Both functions have 4 parameters: 3 parameters can be passed in the anonymous function item (current item), index (index of the current item), arr (original array), and an optional parameter this
- This in anonymous function points to window by default
- Callback function will not be called for empty arrays
- The original array will not be changed (can be changed in some cases)
2. forEach
(1) No return value.
var a = [1,2,3,4,5] var b = ((item) => { item = item * 2 }) (b) // undefiined
(2) The situation where the original array can be changed
Let’s see a few examples below:
var a = [1,2,3,4,5] ((item) => { item = item * 2 }) (a) // [1,2,3,4,5]
The original array has not changed here.
var a = [1,'1',{num:1},true] ((item, index, arr) => { item = 2 }) (a) // [1,'1',{num:1},true]
When modifying the item value here, the original array is still not modified.
var a = [1,'1',{num:1},true] ((item, index, arr) => { = 2 item = 2 }) (a) // [1,'1',{num:2},true]
When modifying a property of an object in the array, it is found that the property has changed.
Why is this happening?
Here we need to introduce the concepts of stack memory and heap memory. For basic data types in JS, such as String, Number, Boolean, Undefined, Null, which exist in the stack memory, and store variable names and corresponding values in the stack memory. Object, Array, Function exists in heap memory, where variable names and reference locations are stored.
In the first example, why can't the original array be modified directly? Because the value of the item is not the corresponding value in the original array, but a new variable recreated, with the same value as the original array.
In the second example, the value of the object in the array has not changed, because although the newly created variable and the object in the original array point to the same address, the value of the new variable is changed, that is, the value of the new object is 2, and the object in the original array is still {num:1}.
In the third example, since the object is a reference type, the new object and the old object point to the same address, the new object turns num into 2, and the objects in the original array are also changed.
var a = [1,2,3,4,5] ((item, index, arr) => { arr[index] = item * 2 }) (a) // [2,4,6,8,10]
Change the value of arr in the callback function, and the original array is changed.
This example is actually the same as Example 3. The arr in the parameter is only a copy of the original array. If you modify an item in the array, the original array will also change because it points to the same reference address. If you assign other values to the parameter arr, the original array will not change.
In fact, if you want to know whether the item and arr in the parameters are recreated variables, you can print them in the callback function.
(3) Applications in vue
I often use this method when processing data, because the data is passed in json format, and I often receive data containing many objects in the array. The data passed to me by the backend sometimes needs to be processed, such as formatting the timestamp to normal time, the code is as follows:
// const formatTime = date => { var newDate = new Date(); (date * 1000); const year = () const month = () + 1 const day = () const hour = () const minute = () const second = () return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':') } const formatNumber = n => { n = () return n[1] ? n : '0' + n } export { formatTime }
// The obtained data format[ {add_time: 1541495677, balance: 14, bn: "300708", cprice: "12.39"} ]
// import axios from 'axios' import { formatTime } from '@/lib/utils' export default { data() { dataList: [] }, methods: { getData() { ('/user?ID=12345') .then(function (res) { if( == 200) { ((item) => { item.add_time = formatTime(item.add_time) } = } }) .catch(function (err) { (err); }); } } }
At this time, the value of the original data also changed, becoming the formatted time.
3. map
(1) Returns a processed new array without changing the value of the original array.
var a = [1,2,3,4,5] var b = ((item) => { return item = item * 2 }) (a) // [1,2,3,4,5] (b) // [2,4,6,8,10]
(2) The situation and principle of changing the original array in map is the same as forEach
(3) Applications in vue
There is a requirement that the recharge amount needs to be randomly subtracted 100 or added 100 on the basis of integers. At this time, I need a processed new array based on the original data.
export default { data() { moneyList: [1000,2000,5000,10000,20000,50000] }, computed: { moneyList_new() { return ((item) => { const random = () > 0.5 ? 1 : -1; return (()*100) * random + item; }) } } }
Just actually render the processed array ~
III. Conclusion
The above is the comparison and practical application of forEach and map. The code is just a demonstration of how to use it and is not completely real. I hope it will be helpful to everyone's learning and I hope everyone will support me more.