19

When I do this:

var testArray  = ["a","b","c"];
console.log(testArray);
console.log("size:" + testArray.length);

I this this printed in my console:

["a", "b", "c"]
size:3 

Which is good. But now when I start splicing with this:

var testArray  = ["a","b","c"];
console.log(testArray);
console.log("size:" + testArray.length);
testArray = testArray.splice(0,1);

This happens to show in my console:

["b", "c", undefined × 1]
size:3 

So first question is why does it mess up my printing of the array even though the splice was after the printing? The size is shown correctly but the "a" is gone and I get an undefined at the end.

So what I wanted to do was to remove the first item in the array. Basically a shift. So I do this:

var testArray  = ["a","b","c"];
console.log(testArray);
console.log("size:" + testArray.length);
testArray = testArray.splice(0,1);
console.log(testArray);
console.log("size:" + testArray.length);

And this is what gets outputted:

["b", "c", undefined × 1]
size:3
["a"]
size:1 

Not only did the size decrease by 2, it deleted everything but the "a". What is going on?

scottt
  • 7,008
  • 27
  • 37
Dragonfly
  • 4,261
  • 7
  • 34
  • 60
  • 3
    Splice returns the "spliced" array. In this case, you're setting `testArray` to the result of the splice, which is the array `["a"]` – Shmiddty Sep 07 '12 at 15:37
  • @Shmiddty Ah thanks! I guess I was using the spliced wrong then. – Dragonfly Sep 07 '12 at 15:38
  • yes, javascript's splice is similar to the way PHP's array_shift works, you remove one, and are returned that one. – Kristian Sep 07 '12 at 15:39
  • You could do something like `testArray = testArray.splice(1);` If you want to simply remove the first item. – Shmiddty Sep 07 '12 at 15:41
  • 2
    The console issue is; http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays – Alex K. Sep 07 '12 at 15:42
  • Interesting about the console issue. But thanks everyone. Solved all my questions! – Dragonfly Sep 07 '12 at 15:43
  • splice will produce very odd results if you need to keep the index. – Alex Mar 27 '13 at 11:46

1 Answers1

31

Dont assign testArray to itself. Simply do:

var testArray  = ["a","b","c"];
console.log(testArray);
console.log("size:" + testArray.length);
testArray.splice(0,1);
console.log(testArray);
console.log("size:" + testArray.length);
James Kleeh
  • 12,094
  • 5
  • 34
  • 61