2

In this JavaScript, why don't i get azbc?

var x = "a-b-c".split('-').splice(1, 0, 'z');
alert(x.join(''));

split returns an array containing a, b and c.

Shouldn't splice insert z after a and gives me azbc?

Why do i get an empty array?

note: i know that what i want can be accomplished by:

var x = "a-b-c".split('-')
x.splice(1, 0, 'z');
alert(x.join(''));

since splice "modifies" the original array itself. shouldn't it modify {a,b,c} to {a,z,b,c} and then be assigned to x?

got it... the code below helped me to understand.

var x = "a-b-c".split('-')
x = x.splice(1, 0, 'z');
alert(x.join(''));
2
  • it returns the removed elements, so no, it wouldn't be assigned to x. The only thing assigned to x is going to be whatever elements are removed, in this case none. The bottom line is if you want to splice an array you have to store it in a variable first otherwise you will lose the result in a chain-type expression like the one you have. Jun 1, 2012 at 6:03
  • JavaScript does not distinguish itself here. Sep 7, 2015 at 12:29

4 Answers 4

6

splice returns the removed items from the array, not the new array:

> x = 'a-b-c'.split('-');
["a", "b", "c"]
> x.splice(1,0,'z');
[]
> x
["a", "z", "b", "c"]
> x.splice(1,1,'x');
["z"]
> x
["a", "x", "b", "c"]
1

Like Paolo said, splice modifies the array in place http://jsfiddle.net/k9tMW/

var array = "a-b-c".split('-');
array.splice(1, 0, 'z');
alert(array.join(''));
1

Mozilla Developer Network-Array splice method - Changes the content of an array, adding new elements while removing old elements.

Returns- An array containing the removed elements. If only one element is removed, an array of one element is returned.

var x = "a-b-c".split('-');
x.splice(1, 0, 'z');
document.write(x + "<br />"); 
1

You have to do like this,

var x = "a-b-c".split('-');
x.splice(1, 0, 'z');
alert(x.join(''));​
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.