Funny behavior of Array.splice ()

I experimented with 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 array b to the third splicing argument, I mean "remove the first two arguments a from index zero and replace them with a b-array." I have never seen passing an array as the third argument to splice () (all the pages I read talk about the argument list), but, well, that seems to be a trick. [1,2] are deleted, and now a is [a, b, c, 3,4,5,6,7,8,9,10]. Then I create another array that 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 deleted [a, b, c, 3], and the array c is added at the beginning. Does anyone know why? I am sure that the solution is trivial, but I do not understand it right now.

+7
javascript arrays array-splice splice
source share
1 answer

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

Using Firebug (or the Chrome console), you see what really happens:

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

The problem here is in jconsole, which simply uses toString() to print arrays, but Array.toString() does not print any [] .

+6
source share

All Articles