Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion with javascript array.splice()

I'm really confused about this.

My understanding was that array.splice(startIndex, deleteLength, insertThing) would insert insertThing into the result of splice() at startIndex and delete deleteLength's worth of entries? ... so:

var a = [1,2,3,4,5];
var b = a.splice(1, 0, 'foo');
console.log(b);

Should give me:

[1,'foo',2,3,4,5]

And

console.log([1,2,3,4,5].splice(2, 0, 'foo'));

should give me

[1,2,'foo',3,4,5]

etc.

But for some reason it's giving me just an empty array? Take a look: http://jsfiddle.net/trolleymusic/STmbp/3/

Thanks :)

like image 523
Trolleymusic Avatar asked Sep 22 '11 16:09

Trolleymusic


People also ask

What does splice () do in JavaScript?

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 difference between array splice () and array slice () method in JavaScript?

slice returns a piece of the array but it doesn't affect the original array. splice changes the original array by removing, replacing, or adding values and returns the affected values.

Is splice () destructive?

splice() method is a destructive array method, which means it modifies the array on which it is called (disclaimer: destructive methods can be risky, especially if you use the array in question elsewhere in your program, so proceed with caution).

Does splice change the array?

slice does not alter the original array. It returns a shallow copy of elements from the original array. Elements of the original array are copied into the returned array as follows: For objects, slice copies object references into the new array.


1 Answers

The "splice()" function returns not the affected array, but the array of removed elements. If you remove nothing, the result array is empty.

like image 89
Pointy Avatar answered Sep 17 '22 19:09

Pointy