slice和splice_让我们清除关于JavaScript中slice(),splice()和split()方法的困惑

slice和splice

JavaScript built-in methods help us a lot while programming, once we understand them correctly. I would like to explain three of them in this article: the slice(), splice() and split() methods. Perhaps because their naming is so similar they are often confused, even among experienced developers.

一旦我们正确理解了JavaScript的内置方法,它们就可以在编程时为我们提供很多帮助。 我想在本文中解释其中的三个: slice()splice()split()方法。 也许是因为它们的命名如此相似,所以即使在经验丰富的开发人员中,它们也常常会造成混淆。

I advise students and junior developers to read this article carefully because these three methods can also be asked in JOB INTERVIEWS.

我建议学生和初级开发人员仔细阅读本文,因为这三种方法也可以在“求职面试”中提出。

You can find a summary of each method in the end. If you prefer, you can also watch the video version below:

您可以在最后找到每种方法的摘要。 如果您愿意,还可以观看以下视频版本:

So let’s start…

让我们开始吧...

JavaScript数组 (JavaScript Arrays)

Firstly, you need to understand how JavaScript arrays work. Like in other programming languages, we use arrays to store multiple data in JS. But the difference is that JS arrays can contain different type of data at once.

首先,您需要了解JavaScript数组如何工作。 与其他编程语言一样,我们使用数组在JS中存储多个数据。 但是不同之处在于, JS 数组可以一次包含不同类型的数据。

Sometimes we need to do operations on those arrays. Then we use some JS methods like slice () & splice (). You can see below how to declare an array in JavaScript:

有时我们需要对这些数组进行操作。 然后我们使用一些JS方法,例如slice()和splice() 。 您可以在下面看到如何在JavaScript中声明数组:

let arrayDefinition = [];   // Array declaration in JS

let arrayDefinition = []; // Array declaration in JS

Now let’s declare another array with different data types. I will use it below in examples:

现在让我们声明另一个具有不同数据类型的数组。 我将在下面的示例中使用它:

let array = [1, 2, 3, "hello world", 4.12, true];

let array = [1, 2, 3, "hello world", 4.12, true];

This usage is valid in JavaScript. An array with different data types: string, numbers, and a boolean.

此用法在JavaScript中有效 。 具有不同数据类型的数组:字符串,数字和布尔值。

片() (Slice ( ))

The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn’t change the original array.

slice()方法复制数组的给定部分,并将复制的部分作为新数组返回。 它不会更改原始数组。

array.slice(from, until);

array.slice(from, until);

  • From: Slice the array starting from an element index

    From: 元素索引开始切片数组

  • Until: Slice the array until another element index

    直到:将数组切片直到另一个元素索引

For example, I want to slice the first three elements from the array above. Since the first element of an array is always indexed at 0, I start slicing “from”0.

例如,我想从上面的数组中切出前三个元素。 由于数组的第一个元素总是索引为0,因此我开始从“ 0 开始切片。

array.slice(0, until);

array.slice(0, until);

Now here is the tricky part. When I want to slice the first three elements, I must give the until parameter as 3. The slice( ) method doesn’t include the last given element.

现在是棘手的部分。 当我想裁前三个元素,我必须给,直到参数为3 片()方法不包括最后一个给定的元素。

array[0] --> 1              // included
array[1] --> 2              // included
array[2] --> 3              // included
array[3] --> "hello world"  // not included

This can create some confusion. That’s why I call the second parameter “until”.

这会造成一些混乱。 这就是为什么我将第二个参数称为“直到”。

let newArray = array.slice(0, 3);   // Return value is also an array

let newArray = array.slice(0, 3); // Return value is also an array

Finally, I assign the sliced Array to the newArray variable. Now let’s see the result:

最后,我将切片的Array分配给newArray变量。 现在让我们看一下结果:

Important Note: the Slice( ) method can also be used for strings.

重要说明: Slice()方法也可用于字符串。

接头() (Splice ( ))

The name of this function is very similar to slice( ). This naming similarity often confuses developers. The splice( ) method changes an array, by adding or removing elements from it. Let’s see how to add and remove elements with splice( ):

该函数的名称与slice()非常相似。 这种命名相似性经常使开发人员感到困惑。 splice()方法通过添加或删除数组来改变数组。 让我们看看如何使用splice( )添加和删​​除元素:

移除元素 (Removing Elements)

For removing elements, we need to give the index parameter, and the number of elements to be removed:

要删除元素,我们需要提供index参数以及要删除的元素数量

array.splice(index, number of elements);

array.splice(index, number of elements);

Index is the starting point for removing elements. Elements which have a smaller index number from the given index won’t be removed:

索引是删除元素的起点 。 给定索引中具有较小索引号的元素将不会被删除:

array.splice(2);  // Every element starting from index 2, will be removed

array.splice(2); // Every element starting from index 2, will be removed

If we don’t define the second parameter, every element starting from the given index will be removed from the array:

如果我们不定义第二个参数,则从给定索引开始的每个元素都将从数组中删除:

As a second example, I give the second parameter as 1, so elements starting from index 2 will be removed one by one each time we call the splice ( )method:

作为第二个示例,我将第二个参数设置为1,因此每次调用splice()方法时,将从索引2开始的元素一一删除:

array.splice(2, 1);

array.splice(2, 1);

After 1st call:

第一次通话后:

After 2nd call:

第二次通话后:

This can continue until there is no index 2 anymore.

这可以继续直到不再有索引2。

添加元素 (Adding Elements)

For adding elements, we need to give them as the 3rd, 4th, 5th parameter (depends on how many to add) to the splice ( ) method:

要添加元素,我们需要将它们作为splice()方法的第3,第4,第5参数(取决于要添加的数量):

array.splice(index, number of elements, element, element);

array.splice(索引,元素数量,元素,元素);

As an example, I’m adding a and b in the very beginning of the array and I remove nothing:

例如,我在数组的开头添加了ab ,但没有删除任何内容:

array.splice(0, 0, 'a', 'b');

array.splice(0, 0, 'a', 'b');

分裂 ( ) (Split ( ))

Slice( ) and splice( ) methods are for arrays. The split( ) method is used for strings. It divides a string into substrings and returns them as an array. It takes 2 parameters, and both are optional.

Slice()splice()方法适用于数组。 split()方法用于字符串 。 它将字符串分成子字符串,并将它们作为数组返回。 它有2个参数,并且都是可选的。

string.split(separator, limit);

string.split(separator, limit);

  • Separator: Defines how to split a string… by a comma, character etc.

    分隔符:定义如何用逗号,字符等分割字符串。

  • Limit: Limits the number of splits with a given number

    限制:限制给定数量的拆分数

The split( ) method doesn’t work directly for arrays. However, we can first convert the elements of our array to a string, then we can use the split( ) method.

split()方法不适用于数组 。 但是,我们可以先将数组的元素转换成字符串,然后再使用split()方法。

Let’s see how it works.

让我们看看它是如何工作的。

Firstly, we convert our array to a string with toString( ) method:

首先,我们使用toString()方法将数组转换为字符串:

let myString = array.toString();

let myString = array.toString();

Now let’s split myString by commas, limit them to three substrings, and return them as an array:

现在,让我们用逗号分割myString 将它们限制为三个子字符串,然后将它们作为数组返回:

let newArray = myString.split(",", 3);

let newArray = myString.split(",", 3);

As we can see, myString is split by commas. Since we limit split to 3, only the first 3 elements are returned.

如我们所见, myString被逗号分隔。 由于我们将split限制为3,因此仅返回前3个元素。

NOTE: If we have a usage like this: array.split(""); then each character of the string will be divided as substrings:

注意:如果我们有这样的用法: array.split(""); 那么该字符串的每个字符将被分为多个子字符串:

摘要: (Summary:)

片() (Slice ( ))
  • Copies elements from an array

    从数组中复制元素
  • Returns them as a new array

    将它们作为新数组返回
  • Doesn’t change the original array

    不更改原始数组
  • Starts slicing from … until given index: array.slice (from, until)

    从…开始切片,直到给定索引: array.slice(从,直到)

  • Slice doesn’t include “until” index parameter

    切片不包含“直到”索引参数

  • Can be used both for arrays and strings

    可以用于数组和字符串
接头() (Splice ( ))
  • Used for adding/removing elements from array

    用于从数组添加/删除元素
  • Returns an array of removed elements

    返回已删除元素的数组
  • Changes the array

    更改数组
  • For adding elements: array.splice (index, number of elements, element)

    用于添加元素: array.splice(索引,元素数,元素)

  • For removing elements: array.splice (index, number of elements)

    用于删除元素: array.splice(索引,元素数)

  • Can only be used for arrays

    只能用于数组
分裂 ( ) (Split ( ))
  • Divides a string into substrings

    将字符串分成子字符串
  • Returns them in an array

    以数组形式返回它们
  • Takes 2 parameters, both are optional: string.split(separator, limit)

    带有2个参数,两者都是可选的: string.split(separator,limit)

  • Doesn’t change the original string

    不更改原始字符串
  • Can only be used for strings

    只能用于字符串

There are many other built-in methods for JavaScript arrays and strings, which make easier to work with JavaScript programming. Next, you can check out my new article about JavaScript Substring Methods.

JavaScript数组和字符串还有许多其他内置方法,这些方法使使用JavaScript编程更容易。 接下来,您可以查看有关JavaScript Substring Methods的新文章。

If you want to learn more about web development, feel free to follow me on Youtube!

如果您想了解有关Web开发的更多信息,请随时 在YouTube上关注我

Thank you for reading!

感谢您的阅读!

翻译自: https://www.freecodecamp.org/news/lets-clear-up-the-confusion-around-the-slice-splice-split-methods-in-javascript-8ba3266c29ae/

slice和splice

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值