.slice()
and .splice()
are similar methods in JavaScript. They look similar, they sound similar, and they do similar things. For those reasons, it’s important to know the differences between them. Also, they’re used very often, so understanding their usage is good to learn early on for any software developer.
.slice()
和.splice()
是JavaScript中类似的方法。 他们看起来相似,听起来相似,并且做类似的事情。 由于这些原因,了解它们之间的差异很重要。 另外,它们的使用频率很高,因此对于任何软件开发人员来说,早日了解它们的用法是一件好事。
In this article we’ll look at how to use them with a specific algorithm scripting challenge. We’ll be inserting elements from one array into another and returning the combined array without mutating the original arrays.
在本文中,我们将研究如何在特定的算法脚本挑战中使用它们。 我们将把元素从一个数组插入到另一个数组中,并返回组合后的数组,而不会改变原始数组。
算法指令 (Algorithm instructions)
You are given two arrays and an index.
您将获得两个数组和一个索引。
Use the array methods
slice
andsplice
to copy each element of the first array into the second array, in order.使用数组方法
slice
和splice
依次将第一个数组的每个元素复制到第二个数组中。
Begin inserting elements at index
n
of the second array.开始在第二个数组的索引
n
处插入元素。
Return the resulting array. The input arrays should remain the same after the function runs.
返回结果数组。 函数运行后,输入数组应保持不变。
function frankenSplice(arr1, arr2, n) {
return arr2;
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
提供的测试用例 (Provided Test Cases)
frankenSplice([1, 2, 3], [4, 5], 1)
should return[4, 1, 2, 3, 5]
.frankenSplice([1, 2, 3], [4, 5], 1)
应该返回[4, 1, 2, 3, 5]
frankenSplice([1, 2, 3], [4, 5], 1)
[4, 1, 2, 3, 5]
。frankenSplice([1, 2], ["a", "b"], 1)
should return["a", 1, 2, "b"]
.frankenSplice([1, 2], ["a", "b"], 1)
应该返回["a", 1, 2, "b"]
。frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)
should return["head", "shoulders", "claw", "tentacle", "knees", "toes"]
.frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)
应该返回["head", "shoulders", "claw", "tentacle", "knees", "toes"]
。- All elements from the first array should be added to the second array in their original order. 第一个数组中的所有元素应按其原始顺序添加到第二个数组中。
- The first array should remain the same after the function runs. 函数运行后,第一个数组应保持不变。
- The second array should remain the same after the function runs. 函数运行后,第二个数组应保持不变。
解决方案1:.slice()、. splice()和散布运算符 (Solution 1: .slice( ), .splice( ), and spread operator)
PEDAC (PEDAC)
Understanding the Problem: We have one input, a string. Our output is also a string. Ultimately, we want to return the input string with the first letter — and only the first letter — of each word capitalized.
了解问题 :我们只有一个输入,一个字符串。 我们的输出也是一个字符串。 最终,我们要返回输入字符串,每个单词的第一个字母(也只有第一个字母)都用大写字母表示。
Examples/Test Cases: Our provided test cases show that we should have a capitalized letter only at the beginning of each word. We need to lower case the rest. The provided test cases also show that we aren’t being thrown any curve balls in terms of weird compound words separated by symbols instead of whitespace. That’s good news for us!
示例/测试用例 :我们提供的测试用例表明,仅在每个单词的开头都应有一个大写字母。 我们需要小写其余的。 所提供的测试用例还表明,对于用符号(而不是空格)分隔的奇怪复合词而言,我们不会遭受任何挑战。 这对我们来说是个好消息!
Data Structure: We are going to have to transform our input string into an array in order to manipulate each word separately.
数据结构 :我们将不得不将输入字符串转换为数组,以便分别操作每个单词。
Let’s have a little chat about .slice()
and .splice()
:
让我们来聊聊.slice()
和.splice()
:
First let’s address .slice()
:
首先让我们解决.slice()
:
.slice()
extracts a section of a string and returns it as a new string. If you call .slice()
on a string without passing it any additional information, it will return the whole string.
.slice()
提取字符串的一部分并将其作为新字符串返回。 如果在字符串上调用.slice()
而不传递任何其他信息,它将返回整个字符串。
"Bastian".slice()
// returns "Bastian"
This will be useful to us in this algorithm scripting challenge because the instructions tell us that we should not directly modify the input arrays. So we’re going to need to make a copy of one of them.
这将对我们在此算法脚本编写挑战中很有用,因为指令告诉我们不要直接修改输入数组。 因此,我们需要复制其中一个。
Now let’s look at .splice()
:
现在让我们看一下.splice()
:
.splice()
changes the contents of an array by removing or replacing existing elements and/or adding new elements.
.splice()
通过删除或替换现有元素和/或添加新元素来更改数组的内容。
We can pass .splice()
several arguments that determine where the deletion begins, how much is deleted, and what is inserted. start
is a number that tells .splice()
at which index to begin deleting elements. deleteCount
tells .splice()
how many elements to delete.
我们可以传递.splice()
几个参数来确定删除从何处开始,删除了多少以及插入了什么。 start
是一个数字,告诉.splice()
从哪个索引开始删除元素。 deleteCount
告诉.splice()
要删除多少个元素。
Wait a second! What if you don’t want to delete anything? What if you just want to insert elements? That’s fine. Just set deleteCount
to zero. Now we can start adding items. Just separate each element with a comma, like so item1, item2, item3, item4
.
等一会儿! 如果您不想删除任何内容怎么办? 如果您只想插入元素怎么办? 没关系。 只需将deleteCount
设置为零即可。 现在我们可以开始添加项目了。 只需用逗号分隔每个元素,例如item1, item2, item3, item4
。
.splice(start, deleteCount, item1, item2, item3, etc.)
Another concept to keep in mind for this algorithm scripting challenge is the spread operator. ES6 gifted us with the spread operator which looks like ellipses — just three dots in a row.
应对此算法脚本挑战要记住的另一个概念是散布运算符 。 ES6为我们提供了看起来像椭圆的传播算子-连续只有三个点。
The spread operator is most commonly used when you want to use the elements of an array as arguments to a function. That’s exactly what we’re going to do with it in this challenge. We don’t want to insert the entire array arr1
into arr2
. We want to insert each element of arr1
into arr2
.
当您想将数组的元素用作函数的参数时,最常用扩散运算符。 这正是我们在此挑战中将要采取的措施。 我们不想将整个数组arr1
插入arr2
。 我们想要将arr1
每个元素插入arr2
。
Algorithm:
算法 :
Create a copy of
arr2
.创建
arr2
的副本。Insert all the elements of
arr1
intoarr2
starting at the index inarr2
specified byn
.插入所有的元素
arr1
成arr2
开始在索引处arr2
通过指定n
。- Return the combined arrays. 返回组合的数组。
Code: See below!
代码 :见下文!
function frankenSplice(arr1, arr2, n) {
// Create a copy of arr2.
let combinedArrays = arr2.slice()
// [4, 5, 6]
// Insert all the elements of arr1 into arr2 beginning
// at the index specified by n. We're using the spread
// operator "..." to insert each individual element of
// arr1 instead of the whole array.
combinedArrays.splice(n, 0, ...arr1)
// (1, 0, ...[1, 2, 3])
// [4, 1, 2, 3, 5, 6]
// Return the combined arrays.
return combinedArrays
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
Without comments:
没有评论:
function frankenSplice(arr1, arr2, n) {
let combinedArrays = arr2.slice()
combinedArrays.splice(n, 0, ...arr1)
return combinedArrays
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
解决方案2:.slice()、. splice()和for循环 (Solution 2: .slice( ), .splice( ), and for loop)
PEDAC (PEDAC)
Understanding the Problem: We have one input, a string. Our output is also a string. Ultimately, we want to return the input string with the first letter — and only the first letter — of each word capitalized.
了解问题 :我们只有一个输入,一个字符串。 我们的输出也是一个字符串。 最终,我们要返回输入字符串,每个单词的第一个字母(也只有第一个字母)都用大写字母表示。
Examples/Test Cases: Our provided test cases show that we should have a capitalized letter only at the beginning of each word. We need to lower case the rest. The provided test cases also show that we aren’t being thrown any curve balls in terms of weird compound words separated by symbols instead of whitespace. That’s good news for us!
示例/测试用例 :我们提供的测试用例表明,我们应该仅在每个单词的开头使用大写字母。 我们需要小写其余的。 所提供的测试用例还表明,对于用符号(而不是空格)分隔的奇怪复合词而言,我们不会遭受任何挑战。 这对我们来说是个好消息!
Data Structure: We are going to have to transform our input string into an array in order to manipulate each word separately.
数据结构 :我们将不得不将输入字符串转换为数组,以便分别操作每个单词。
Let’s have a little chat about .slice()
and .splice()
:
让我们来聊聊.slice()
和.splice()
:
First let’s address .slice()
:
首先让我们解决.slice()
:
.slice()
extracts a section of a string and returns it as a new string. If you call .slice()
on a string without passing it any additional information, it will return the whole string.
.slice()
提取字符串的一部分并将其作为新字符串返回。 如果在字符串上调用.slice()
而不传递任何其他信息,它将返回整个字符串。
"Bastian".slice()
// returns "Bastian"
This will be useful to us in this algorithm scripting challenge because the instructions tell us that we should not directly modify the input arrays. So we’re going to need to make a copy of one of them.
这将对我们在此算法脚本编写挑战中很有用,因为指令告诉我们,我们不应该直接修改输入数组。 因此,我们需要复制其中一个。
Now let’s look at .splice()
:
现在让我们看一下.splice()
:
.splice()
changes the contents of an array by removing or replacing existing elements and/or adding new elements.
.splice()
通过删除或替换现有元素和/或添加新元素来更改数组的内容。
We can pass .splice()
several arguments that determine where the deletion begins, how much is deleted, and what is inserted. start
is a number that tells .splice()
at which index to begin deleting elements. deleteCount
tells .splice()
how many elements to delete. Wait a second! What if you don’t want to delete anything? What if you just want to insert elements? That’s fine. Just set deleteCount
to zero. Now we can start adding items. Just separate each element with a comma, like so item1, item2, item3, item4
.
我们可以传递.splice()
几个参数来确定删除从何处开始,删除了多少以及插入了什么。 start
是一个数字,告诉.splice()
从哪个索引开始删除元素。 deleteCount
告诉.splice()
要删除多少个元素。 等一会儿! 如果您不想删除任何内容怎么办? 如果您只想插入元素怎么办? 没关系。 只需将deleteCount
设置为零即可。 现在我们可以开始添加项目了。 只需用逗号分隔每个元素,例如item1, item2, item3, item4
。
.splice(start, deleteCount, item1, item2, item3, etc.)
Unlike in the previous solution, we won’t be using the spread operator here. We’ll be using a for loop instead to pluck each element one at a time from arr1
and insert them into arr2
.
与以前的解决方案不同,我们在这里将不使用传播运算符。 我们将使用for循环,一次从arr1
抽出每个元素,并将它们插入到arr2
。
The trick here is to increment n
by 1 each time the loop runs or else the elements of arr1
will not end up in the right order when inserted into arr2
.
这里的技巧是每次循环运行时将n
递增1,否则当arr1
的元素插入arr2
时,它们将不会以正确的顺序结束。
Algorithm:
算法 :
Create a copy of
arr2
.创建
arr2
的副本。Using a for loop, insert each element of
arr1
intoarr2
starting at indexn
.使用for循环,从索引
n
开始将arr1
每个元素插入到arr2
。Increment
n
by 1 each time the loop runs.每次循环运行时,将
n
递增1。- Return the combined arrays. 返回组合的数组。
Code: See below!
代码 :见下文!
function frankenSplice(arr1, arr2, n) {
// Create a copy of arr2.
let combinedArrays = arr2.slice()
// Using a for loop, insert each element of arr1
// into combinedArrays starting at index n.
for (let i = 0; i < arr1.length; i++) {
combinedArrays.splice(n, 0, arr1[i])
// [4, 5, 6].splice(1, 0, 1)
// [4, 1, 5, 6].splice(2, 0, 2)
// [4, 1, 2, 5, 6].splice(3, 0, 3)
// [4, 1, 2, 3, 5, 6]
// increment n by 1 each time the loop runs
n++
}
// Return the combined arrays.
return combinedArrays
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
Without comments:
没有评论:
function frankenSplice(arr1, arr2, n) {
let combinedArrays = arr2.slice()
for (let i = 0; i < arr1.length; i++) {
combinedArrays.splice(n, 0, arr1[i])
n++
}
return combinedArrays
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
If you have other solutions and/or suggestions, please share in the comments!
如果您有其他解决方案和/或建议,请分享评论!
本文是freeCodeCamp算法脚本系列文章的一部分。 (This article is a part of the series freeCodeCamp Algorithm Scripting.)
本文引用了freeCodeCamp基本算法脚本编写:Slice和Splice (This article references freeCodeCamp Basic Algorithm Scripting: Slice and Splice)
You can follow me on Medium, LinkedIn, and GitHub!
您可以在Medium , LinkedIn和GitHub上关注我!
翻译自: https://www.freecodecamp.org/news/how-to-slice-and-splice-arrays-in-javascript-72bbca45006/