最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - array.length-=1 vs array.pop() - Stack Overflow

programmeradmin7浏览0评论

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?

Share Improve this question edited Aug 24, 2019 at 3:43 jpyams 4,4049 gold badges43 silver badges70 bronze badges asked Jul 6, 2019 at 16:56 RaptorDeveloperRaptorDeveloper 3252 silver badges14 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 8

Some differences:

  • pop returns the value of the entry that you're removing, assigning to length doesn't.

  • pop is a method call; assigning to length is an assignment operation.

  • pop on an array whose length is 0 returns undefined and doesn't change the array. array.length -= 1 on an array with a length of 0 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 ...

发布评论

评论列表(0)

  1. 暂无评论