简体   繁体   中英

Are there differences between [...array].map(...) and [...array.map(...)] in JavaScript?

I can't quite understand the differences between [...array].map(...) and [...array.map(...)] . Are they any different? If yes, why and how?

  • [...array].map(...) will generate a new shallow copy of an array ( [...array] ) and then .map over it and return a brand new array as the return value.
  • [...array.map(...)] will .map over the original array, which will return a new array, and then immediately make a shallow copy of the new array ( [...array.map(...)] ). I must admit, I don't really understand the use case for this approach-- because .map itself is returning a brand new array that no other variable should be holding a reference to, I don't see any value in immediately casting a shallow copy of it.

(Also, as pointed out by chazsolo in the comments, if array were not an array, but in fact some other type like a Set , the [...array.map(...)] approach would actually throw an error, as Set instances have no .map method).

Well [...array.map(...)] is the same as array.map(...) except that it does an extra unnecessary spread/copy after the mapping is done.

The [...array].map(...) has an small difference, due to the 3rd parameter passed in map ( the array it self ).

And as mentioned in another comment, by @chazsolo, this case will handle cases where the array variable is not an array, so it does not have the map method, but can be iterated and the spread will create an array out of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM