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.
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() .
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.
splice(a,b,...) method in JavaScript adds or removes items to/from array.
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.
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 []
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With