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 :)

有帮助吗?

解决方案

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

其他提示

The array.splice function splices an array returns the elements that were removed. Since you are not removing anything and just using it to insert an element, it will return the empty array.

I think this is what you are wanting.

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

splice() modifies the source array and returns an array of the removed items. Since you didn't ask to remove any items, you get an empty array back. It modifies the original array to insert your new items. Did you look in a to see what it was? Look for your result in a.

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

In a derivation of your jsFiddle, see the result in a here: http://jsfiddle.net/jfriend00/9cHre/.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top