Confused about adding Items Using splice()

I’m lil bit confused about using splice() to add elements to an array:

  • It has been mentioned that splice() takes 3 parameters at most, and we know that parameters are separated by comma, how could I define 4 parameters to pass the challenge?
  • I tried to pass the 2 elements as an array but it doesn’t work …

Weird. Your solution works for me

1 Like

So what?! :sweat_smile:

Here’s the code in my browser:


Here’s the result:

Do you get any error message?

1 Like

Hey, @systemry420,
I think your code works but you are confused about working of splice().

I’ll try to explain you how splice works,
splice() takes arguments as follows:

splice(
index from where you want to start removing elemmets, 
number of element(s) you want to remove,
here you can add any number of items  you want and they will be added to array in place of removed items
)

For example if i do:

var arr = [1,2,3,4,5];
arr.aplice(1,2,9,"hello","world","hey");

Here is how it goes,

  1. We will start removing items from index 1 that is from second element onwards.
  2. We will remove 2 items from the array arr.
  3. At this stage arr will be [1,4,5]
  4. But, we have also entered items we wish to replace the removed items with. So, those items will be added.

Can you try to tell me, how will arr look like now?
Hope this helps.

2 Likes

That code should work, so try resetting the code and entering it again. If it still doesn’t work try clearing your browser’s cache as well.

1 Like

@dlaan07
I’m asking why we can specify more arguments, and it works that way, although it’s mentioned that it takes only 3 parameters.

@aditya_p ok, got it bro :slightly_smiling_face:
So it will look like:
[1, 9, “hello”, “world”, “hey”, 4,5]

1 Like

@systemry420 Glad that i could help.

And yes, you have got it right.
Well done.

1 Like

Oh wait, right :sweat_smile:
Sorry for not answering your question.

1 Like