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,.
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 know
So you would say .splice(5, 5, "know")
Can also refer to MDN here . 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? would it be something like this :
.splice(5, 1, "know";2,1,"tomatoe";6,1,"cheese") ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.