Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Funny behaviour of Array.splice()

I was experimenting with the splice() method in jconsole

a = [1,2,3,4,5,6,7,8,9,10]
1,2,3,4,5,6,7,8,9,10

Here, a is a simple array from 1 to 10.

b = ['a','b','c']
a,b,c

And this is b

a.splice(0, 2, b)
1,2
a
a,b,c,3,4,5,6,7,8,9,10

When I pass the array b to the third argument of splice, I mean "remove the first two arguments of a from index zero, and replace them with the b array". I've never seen passing an array as splice()'s third argument (all the guide pages I read talk about a list of arguments), but, well, it seems to do the trick. [1,2] are removed and now a is [a,b,c,3,4,5,6,7,8,9,10]. Then I build another array, which I call c:

c = ['one','two','three']
one,two,three

And try to do the same:

a.splice(0, 2, c)
a,b,c,3
a
one,two,three,4,5,6,7,8,9,10

This time, 4 (instead of 2) elements are removed [a,b,c,3] and the c array is added at the beginning. Someone knows why? I'm sure the solution is trivial, but I don't get it right now.

like image 582
janesconference Avatar asked Dec 01 '10 11:12

janesconference


People also ask

What does array Splice do?

Array.prototype.splice() The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice() .

What is the use of splice () method returns a section of an array?

The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.

What is the use of splice () method in Java?

splice(a,b,...) method in JavaScript adds or removes items to/from array.

What's the difference between array splice () and array slice () methods?

Slice is used to get a new array from the original array whereas the splice is used to add/remove items in the original array. The changes are not reflected in the original array in the case of slice and in the splice, the changes are reflected in the original array.


1 Answers

Array.splice does not support an array as the third parameter.
Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice

Using Firebug (or Chrome's Console), one sees what really happens:

a.splice(0, 2, b)
> [1, 2]
a
> [["a", "b", "c"], 3, 4, 5, 6, 7, 8, 9, 10]

Problem here is jconsole, which just uses toString() to print out the arrays, but Array.toString() does not print any [].

like image 67
Ivo Wetzel Avatar answered Oct 03 '22 14:10

Ivo Wetzel