Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript console printing not working when assigning splice of array to itself

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?

like image 887
Dragonfly Avatar asked Sep 07 '12 15:09

Dragonfly


People also ask

Does splice work on arrays?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

How JavaScript splice works in array?

splice() JS Array Method. The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.

Is splice destructive JavaScript?

splice() method is a destructive array method, which means it modifies the array on which it is called (disclaimer: destructive methods can be risky, especially if you use the array in question elsewhere in your program, so proceed with caution).

What is the alternative of splice in JavaScript?

Alternative of Array splice() method in JavaScript If the count is not passed then treat it as 1. Run a while loop till the count is greater than 0 and start removing the desired elements and push it in a new array. Return this new array after the loop ends.


1 Answers

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);
like image 161
James Kleeh Avatar answered Sep 20 '22 16:09

James Kleeh