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?
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):
Both lines of code remove the first element from the array, and return the removed element, they are both supported in all major browsers.
You should use the second one, and the code will be more readable indeed.
来源:https://stackoverflow.com/questions/10742369/javascript-shift-versus-splice-are-these-statements-equal