I know that array is some kind of an object, but it also has numeric indexes. And arr.length
is a property, which returns not the number of elements in the array, but the last index+1. We can remove the last element using decrement of length
or function pop()
. And the question is: What's the difference between these methods?
I know that array is some kind of an object, but it also has numeric indexes. And arr.length
is a property, which returns not the number of elements in the array, but the last index+1. We can remove the last element using decrement of length
or function pop()
. And the question is: What's the difference between these methods?
-
you get the item with
pop
...? what is the changing of length for? – Nina Scholz Commented Jul 6, 2019 at 16:57 - 1 Is it an antipattern to set an array length in JavaScript? and Javascript array length modification implications – adiga Commented Jul 6, 2019 at 17:00
2 Answers
Reset to default 8Some differences:
pop
returns the value of the entry that you're removing, assigning tolength
doesn't.pop
is a method call; assigning tolength
is an assignment operation.pop
on an array whose length is0
returnsundefined
and doesn't change the array.array.length -= 1
on an array with alength
of0
causes an error.
.pop()
also returns the last element (which is often wanted):
const last = array.pop();
// vs
const last = array[array.length - 1];
array.length -= 1;
Now you can decide yourself which one of the above is more readable ...
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744248260a4565041.html
评论列表(0条)