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

I know that array is some kind of an object, but it also has numeric indexes. And arr.length is a prope

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 ...

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744248260a4565041.html

相关推荐

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

    I know that array is some kind of an object, but it also has numeric indexes. And arr.length is a prope

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信