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?
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
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.
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).
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With