[英]Are there differences between [...array].map(...) and [...array.map(...)] in JavaScript?
I can't quite understand the differences between [...array].map(...)
and [...array.map(...)]
.我不太明白
[...array].map(...)
和[...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(...)
将生成一个新的数组浅表副本( [...array]
),然后在其上.map
并返回一个全新的数组作为返回值。[...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(...)]
). [...array.map(...)]
将.map
覆盖在原始数组上,这将返回一个新数组,然后立即制作新数组的浅表副本( [...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..map
本身正在返回一个全新的数组,没有其他变量应该引用它,我看不出立即转换的任何价值它的浅拷贝。 (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). (此外,正如chazsolo在评论中指出的那样,如果
array
不是数组,但实际上是其他类型,例如Set
,则[...array.map(...)]
方法实际上会引发错误,因为Set
实例没有.map
方法)。
Well [...array.map(...)]
is the same as array.map(...)
except that it does an extra unnecessary spread/copy after the mapping is done.那么
[...array.map(...)]
与array.map(...)
相同,只是它在映射完成后会进行额外的不必要的传播/复制。
The [...array].map(...)
has an small difference, due to the 3rd parameter passed in map ( the array it self ).由于在 map (它自己的数组)中传递了第三个参数,
[...array].map(...)
有一个小的差异。
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.正如@chazsolo 在另一条评论中提到的那样,这种情况将处理
array
变量不是数组的情况,因此它没有map
方法,但可以迭代并且传播将创建一个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.