如何在JavaScript中切片和拼接数组
.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 runsn++}// 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/
相关文章:

jQuery中getJSON跨域原理详解
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp28 jQuery中getJSON跨域原理详解 前几天我再开发一个叫 河蟹工具条 的时候,其中有个功能就是获取本页面的短网址。 这个想法是好的,可是在我付诸于行动的时候,发…

样式集(七)仿微信发现页样式
效果图: <!--pages/find/find.wxml--><include src"/components/common/common" /> <view class"item" catchtap"nav1"><image class"icon" mode"widthFix" src"/images/icon_5.png&q…

html向js传递id
html获取id方法: <div id"thediv1" style"display:block" onclick"ceshi(this.id)">技术A组</div> this.id ------>本身id转载于:https://www.cnblogs.com/wanlibingfeng/p/7613575.html

javascript功能_功能性JavaScript简介
javascript功能Hey everybody! I’ve written a book called Discover Functional JavaScript, and it’s now ready in both paperback and Kindle formats.大家好! 我已经写了一本书《 发现功能JavaScript》 ,现在已经可以使用平装本和Kindle格式。 A…

样式集,小程序群聊,聊天室样式,效果图
效果图 注:(码云 group_chat_yun ) 代码: <!-- <view class"top"><image class"page_editright" catchtap"navBack" mode"widthFix" src"/images/editright.png&quo…

GeoQuiz项目的开发与总结2
时间过得很快,第二阶段的学习结束了。 本周的主要工作是完成了Geoquiz项目的剩余部分。 首先是学到了些什么,最主要的是工作的流程,然后是界面的布局,菜单栏的设计到等。当然我觉得我学到的应该是工作制作的思维方式吧。 再来说说…

【12.16】VC++调用Word OLE进行自动化生成报表
! 12-16更新 初始化博客转载于:https://www.cnblogs.com/miki-52/p/5052689.html

python timber_如何使用Timber更有效地记录日志
python timberby Ayusch Jain通过Ayusch Jain 如何使用Timber更有效地记录日志 (How to log more efficiently with Timber) Logging is one of the most used utilities in the Android framework. It is really helpful in debugging your code when debugging by break-poi…

node 实现blog博客
https://cnodejs.org/topic/581b0c4ebb9452c9052e7acb转载于:https://www.cnblogs.com/zhangshuda/p/7640363.html

小程序输入框导致界面上移,在输入的时候固定住页面的解决代码
效果: 代码: <view class"comment" style"bottom:{{bottom}}px"><view class"emoji_block" wx:if{{emoji_block_show}}><view wx:for{{connectemoji}} catchtap"add_biaoqing" id"{{item}}…

react中纯函数_如何在纯React中创建电子邮件芯片
react中纯函数by Andreas Remdt由Andreas Remdt 如何在纯React中创建电子邮件芯片 (How to create email chips in pure React) Imagine that you, the good-looking developer (yes, I’m talking to you!), want to build an invitation form where users can add one or mo…
servlet程序HTTP Status 500 - Error instantiating servlet class 解决
一、项目存放路径问题(最常见) 在安装Tomcat时,运行程序都正常,但却打不开http://localhost:8080/,在Tomcat目录webapps下也找不到自己做的项目,这时因为你做的项目没有部署到webapps目录下,倒霉的时候就会遇到报错HTT…

ASP.NET将原始图片按照指定尺寸等比例缩放显示图片
网站上可能会有很多图片,比如产品图片等,而且他们可能大小不一,宽度和高度也不一定一样,有的很大有的很小。如果放在一张网页上,可能会破坏版面,但是如果强制让他们按照指定的宽度和高度显示,因…

前端开发框架选择
Vue Vant 适用场景:开发移动端 (vue) 上手难度:1 Vant是一款很好用的移动端UI框架,非常轻便,适合小型项目 https://vant-contrib.gitee.io/vant/#/zh-CN/ 微信小程序 适用场景:微信小程序(小程序原生框架…

anki_Anki如何挽救我的工程生涯
ankiby Jeffrey Shek通过Jeffrey Shek Anki如何挽救我的工程生涯 (How Anki saved my Engineering Career) I was burned out and my software career was stalling just three years in. My memory sucked. Was my poor memory from stress, lack of sleep or was it always …

信息安全系统设计基础期末总结
【博客汇总】 一、每周读书笔记链接汇总 •[第二周读书笔记] http://www.cnblogs.com/20135302wei/p/4842480.html •[第三周读书笔记] http://www.cnblogs.com/20135302wei/p/4858760.html •[第四周读书笔记] http://www.cnblogs.com/20135302wei/p/4870113.html •[第五周读…

方法 retrun 异步的值,创建一个变量直接等于一个异步方法返回的值
需求:我想创建一个变量,他的值是一个openid, openid 从 getOpenid (封装的一个异步方法) 里面返回,通常调用 getOpenid ,会返回一个Promise 对象,.then 之后才能得到值,例如: //模拟一个异步方…

ps混合模式glsl代码
https://github.com/jamieowen/glsl-blend 转载于:https://www.cnblogs.com/guochen/p/7645227.html

应用程序启动器 标记为信任_为什么您今天不能信任应用程序-以及如何解决它...
应用程序启动器 标记为信任亲爱的每家高科技公司,请窃取这个想法 (Dear Every Single Tech Company, Please Steal This Idea) When you send a photo to someone, your messaging app actually first sends the photo to an app’s server, which then sends the p…

小程序客服自动回复图片,云开发的实现
小程序先开通云开发,创建一个文件夹,并配置为云函数的目录 小程序客服自动回复图片实现步骤: 1.云函数接收消息推送 第一步:开发者工具云开发控制台中增加配置 打开云开发控制台,到设置 tab 中选择全局设置 - 添加消…

ORA-12514: TNS: 监听程序当前无法识别连接描述符中请求的服务解决
方法1: a、通过oracle 工具 Net Configuration Assistant 重新配置监听,注意如果有双网卡请配置第一块网上IP。如何知道哪一块是一块网卡,可以通过ipconfig命令查看最上面的ip就是一块网卡的 b、通过Net Configuration Assistant 工具配置 “…

r语言 编辑 d3.js_d3.js的语言介绍
r语言 编辑 d3.jsby Matt Oxley由马特奥克斯利(Matt Oxley) d3.js的语言介绍 (A linguistic introduction to d3.js) 如何从一个试探者变成一个自信的用户 (How to go from a tentative to a confident user) d3.js is a fantastic library — but I can honestly tell you th…

【Luogu3041】视频游戏的连击(AC自动机,动态规划)
题面链接 题解 首先构建出AC自动机 然后在AC自动机上面跑DP 转移很显然从Trie树的节点跳到他的儿子节点 但是要注意一个问题, 在计算的时候,每一个节点加入后能够 造成的贡献 要加上他的子串的贡献 至于DP: 设f[i][j]表示已经使用了i个字母 当…

拥抱高效、拥抱 Bugtags 之来自用户的声音(三)
小编按:这是一篇 Bugtags 用户来稿,主要是介绍了使用 Bugtags 前后对测试及解决 Bug 所带来的变化,感谢山西农业大学 - 高正炎同学对 Bugtags 的信赖和支持。小编在这里诚邀各位热心用户向我们投稿,说出你使用 Bugtags 的故事。 0…

小程序打开文档标题乱码处理
先下载,自定义临时文件目录名称,然后再打开就可以了。 wx.downloadFile({url: https://xxx.cn/sfxy.docx, //仅为示例,并非真实的资源filePath: wx.env.USER_DATA_PATH /这是自定义标题.docx,success(res) {console.log(0, res)wx.openDocum…

我是“真正的”软件工程师吗?
by Sun-Li Beatteay通过孙丽贝蒂 我是“真正的”软件工程师吗? (Am I a “real” Software Engineer yet?) Am I a “real” Software Engineer yet?我是“真正的”软件工程师吗? This question has haunted me for years. And it seems I’m not al…

ntpdate[31915]: the NTP socket is in use, exiting
[rootmaster local]# ntpdate cn.pool.ntp.org 10 Oct 13:24:36 ntpdate[31915]: the NTP socket is in use, exitingcron 作业中运行 ntpdate,以便大约每隔一小时就设置一次本地时间。最近,我每次运行该命令时都会收到下列错误消息。 ntpdate[31915]: t…

小程序云开发更新数组的指定对象的值
云开发,在小程序实现 代码说明‘: 在这里,数据集合 groupList 中的 userList 是一个用户列表数组,我要更新数组中,openid 等于我的openid 的在线状态为 true。 先查询条件,集合里面的 _id 等于我传的id&a…
Unreal Engine 4 RenderTarget制作Live Camera效果
Unreal Engine 4 RenderTarget制作Live Camera效果 先上效果: Live Camera我不知道怎么翻译。反正意思就是将一个摄影机的Image渲染到一个2D平面上。 以下介绍下详细的实现方法: 1.创建一个Scene Capture 2D对象 将这个对象拖动到合适的地方。2.创建Re…

领导让我重构代码_领导不是由代码构成
领导让我重构代码The team leader is a key figure in a team of developers. It is a difficult role, involving both technical and social skills. This is the reason why not everyone is tailored for it.团队负责人是开发人员团队中的关键人物。 这是一项艰巨的任务&am…