admin管理员组

文章数量:1391969

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 acplished 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(''));

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 acplished 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(''));
Share Improve this question edited Jun 1, 2012 at 6:05 Ray Cheng asked Jun 1, 2012 at 5:51 Ray ChengRay Cheng 12.6k16 gold badges78 silver badges139 bronze badges 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. – Paolo Bergantino Commented Jun 1, 2012 at 6:03
  • JavaScript does not distinguish itself here. – superluminary Commented Sep 7, 2015 at 12:29
Add a ment  | 

4 Answers 4

Reset to default 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"]

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

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

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 />"); 

You have to do like this,

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

本文标签: javascriptwhy calling split and splice gives empty arrayStack Overflow