Till Till - 5 months ago 43
Javascript Question

js. splice returns removed item?

I am having problem of understanding splice and I want to have help.

Please check the jsfiddle.

http://jsfiddle.net/fantill/TbpWf/1/

value = "c, a, b"
value = value.split(',').splice(1, 1).join(',')
alert(value);


the value is supposed have return
'c, b'
.

However, it returns
'a'
;

What is wrong with this method?

Thank you very much.

Answer Source

.splice does return the removed item. However, it also manipulates the array internally. This prevents you from chaining anything to .splice; you must do two separate calls:

value = value.split(',');
value.splice(1, 1);
console.log(value.join(','));

If you do value = value.splice(...), value is overridden, and the array is lost!