简体   繁体   English

用JavaScript中的.splice()替换多个元素

[英]replace multiple elements with .splice() in javascript

I am pretty new to Javascript and i am doing a course on it atm. 我对Java语言还很陌生,我正在上有关atm的课程。 I am searching for a way to replace multiple items in an array with 1 item but i only know how to replace a single one.here is my snipped: 我正在寻找一种方法可以用一个项目替换数组中的多个项目,但我只知道如何替换单个项目。

 let secretMessage = ["Learning", "isn't", "about", "what", "you", "get", "easily", "the", "first", "time,", "it's", "about", "what", "you", "can", "figure", "out.", "-2015,", "Chris", "Pine,", "Learn", "JavaScript"]; secretMessage.pop(); secretMessage.push('to','program'); secretMessage[6] = 'right'; secretMessage.shift(); secretMessage.unshift('Programming'); 

and this is what i am supposed to do: Use an array method to remove the strings get, right, the, first, time,, and replace them with the single string know,. 这就是我应该做的:使用数组方法删除字符串get,right,the,first,time,并用一个已知的字符串替换它们。

The .splice() method lets you replace multiple elements in an array with one, two, or however many elements you like. .splice()方法使您可以将数组中的多个元素替换为一个,两个或.splice()多个元素。 Just use the syntax: 只需使用以下语法:

.splice(startingIndex, numDeletions, replacement1, replacement2, ... )

where: 哪里:

  • startingIndex is the index of the array that contains the first element you want to remove startingIndex是包含要删除的第一个元素的数组的索引
  • numDeletions is the number of consecutive items in the array you want to remove numDeletions是要删除的数组中连续项目的数量
  • replacement1 , replacement2 , ... (however many) are the elements you wish to add to the array, beginning at startingIndex replacement1replacement2... (多少个)是您希望添加到数组中的元素,起始于startingIndex

In your case: 在您的情况下:

  • get is at index 5 get在索引5
  • get , easily , the , first , time is 5 Strings consecutively geteasilythefirsttime5弦连续
  • only want one replacement: the String know 只想要一个替换:字符串know

So you would say .splice(5, 5, "know") 所以你会说.splice(5, 5, "know")

Can also refer to MDN here . 也可以在这里参考MDN。 Cheers! 干杯!

Thank you so much!but could you give me an example with items not in a row for example 5 7 9 and more than on replacement-word? 非常感谢您!但是您能给我一个例子,列出不连续的项目,例如5 7 9,而不是替换词吗? would it be something like this : 会是这样的吗:

.splice(5, 1, "know";2,1,"tomatoe";6,1,"cheese") ? .splice(5,1,“知道”; 2,1,“番茄”; 6,1,“奶酪”)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM