JS map function in the array to note that the details (when the type of array element containing reference process)

If that, and today we found a lot of tutorials and documentation does not make clear the details of a map function when in use, such as for a description of the map function, the rookie tutorial mentioned

Note:  the Map () does not alter the original array.

 For example, the following examples:

var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(array1);
// expected output: Array [1, 4, 9, 16]
console.log(map1);
// expected output: Array [2, 8, 18, 32]

 But this is for such a case is when the array elements are the basic types, and if the array elements include the object type, then:

let arr = [
  {a: 1, b: 2},
  {a: 3, b: 4},
]
arr.map((item, index) => {
  if (index === 0) {
    item.a = item.a + 1
    item.c = true
  } else {
    item.c = false
  }
  return item
})
console.log('ss', arr)

We found that the output result is this

As the value of the object property type element because processing callback function map array itself varies arr

 The following example is more obvious:

let arr2 = [3, 9, {attr: 2}]
arr2.map((item, index) => {
  if (index === 0) {
    item = item + 1
  }
  if (index === 2 ) {
    item.attr = false
  }
   return item
})
console.log('arr2', arr2)

Output:

 Found arr2 map function call process result from the print element attribute itself, as an element value of the basic types of callback after treatment did not change, and the third element of the object type because, when the process is assigned to affect arr2 itself.

Therefore, when we summarize the role of map method is more accurate to say:

map Without modifying the original array itself calls it (of course, can  callback change the implementation of the original array) 

 Also on map usage scenario ( above example does not demonstrate the results in order to facilitate the process returns map assigned to a new array, in fact, use is preferably to have a new map array to receive a return value, the function like filter Similarly, with the forEach otherwise would be more appropriate ):

Because the map creates a new array, when you do not intend to use the new array returned but use map is contrary to the original intention of the design, use, or for-of forEach instead. You should not use the map: A) you're not going to use the new array is returned, or / and B) you do not have a return value from the callback function.

 

Reference: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map

 

发布了24 篇原创文章 · 获赞 20 · 访问量 3万+

Guess you like

Origin blog.csdn.net/a715167986/article/details/102833413
Recommended