扩展语法与切片方法 [英] spread syntax vs slice method

查看:85
本文介绍了扩展语法与切片方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解以下方法中扩展语法与切片方法之间的区别。

I was trying to understand what is the difference between spread syntax vs slice method in the following approach.

假设我想制作一个数组的实际副本,我可以使用扩展语法轻松地做到这一点

suppose I want to make an actual copy of an array, I can probably easily do it using spread syntax

var fruits = ["Banana", "Chips" , "Orange", "Lemon", "Apple", "Mango"]
var newCitrus = [...fruits]

如果我在console.log这个

If I console.log this

["Banana", "Chips", "Orange", "Lemon", "Apple", "Mango"] 

但我也可以使用切片创建一个数组副本方法。考虑到上面的相同数组,如果我做这样的事情......

but I can also create a copy of an array using the slice method. Considering the same array above, if I do something like this...

var citrus = fruits.slice(0);

然后控制台记录它,它会给我完全相同的数组,我会通过它传播语法

and then console log it, it will give me exactly the same array which I would've got through spread syntax

["Banana", "Chips", "Orange", "Lemon", "Apple", "Mango"] 

由于它们的代码/写入时间差不多,这有什么区别?我通常应该选择哪种方法?

Since both of them takes about the same time to code/write, What is the difference here? which approach should I usually choose?

推荐答案

性能除了切片只是<$ c $上的一个函数c> Array.prototype 所以它只适用于数组。另一方面,Spread语法适用于任何可迭代的(满足可迭代协议)因此它可以在任何字符串数组 TypedArray 地图设置。您还可以轻松创建自定义迭代

Performance aside slice is just a function on Array.prototype so it will work only for arrays. Spread syntax on the other hand will work for any iterable (object which satisfy iterable protocol) so it will work out of the box on any String, Array, TypedArray, Map and Set. You can also easily create custom iterables.

传播语法也可用于制作对象的浅克隆:

Spread syntax can also be used to make shallow clones of objects:

const obj = { foo: 'bar', baz: 42 };
const clone = { ...obj1 };
obj.foo === clone.foo // true
obj.baz === clone.baz // true
obj === clone         // false (references are different)

这篇关于扩展语法与切片方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆