I just want to confirm if the following two Javascript statements produces the same results, as it seems to me:
First:
var element = my_array.splice(0,1)[0];
Second:
var element = my_array.shift();
I want to substitute the first by the second, in my own code, to improve readability. Can I do this?
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.
slice returns a piece of the array but it doesn't affect the original array. splice changes the original array by removing, replacing, or adding values and returns the affected values.
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).
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
They will have the same effect, yes. splice(0, 1)
will remove the first element from my_array
and return a new array containing that element. shift
will do the same, but return the element itself, not an array.
shift
is more readable (in my opinion) and is also significantly faster (in Chrome at least):
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