最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

replace multiple elements with .splice() in javascript - Stack Overflow

programmeradmin5浏览0评论

I am pretty new to Javascript and i am doing a course on it 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');

I am pretty new to Javascript and i am doing a course on it 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,.

Share Improve this question edited Dec 9, 2017 at 4:06 dippas 60.6k15 gold badges123 silver badges132 bronze badges asked Dec 9, 2017 at 3:53 itsolidudeitsolidude 1,2793 gold badges12 silver badges25 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 4

The .splice() method lets you replace multiple elements in an array with one, two, or however many elements you like. 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
  • numDeletions is the number of consecutive items in the array you want to remove
  • replacement1, replacement2, ... (however many) are the elements you wish to add to the array, beginning at startingIndex

In your case:

  • get is at index 5
  • get, easily, the, first, time is 5 Strings consecutively
  • only want one replacement: the String know

So you would say .splice(5, 5, "know")

Can also refer to MDN here. Cheers!

发布评论

评论列表(0)

  1. 暂无评论