Funny behaviour of Array.splice()
Asked Answered
T

1

7

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.

Telegony answered 1/12, 2010 at 11:31 Comment(0)
W
6

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 [].

Wire answered 1/12, 2010 at 11:40 Comment(1)
Great. I was misleaded by the "flat" jconsole answers (where everything seemed to be a single array, not the b array as the first member of the first one, a). All is clear now.Telegony

© 2022 - 2024 — McMap. All rights reserved.