search

Home  >  Q&A  >  body text

What is the return value after pop() push() unshift() shift() operates on an array in Javascript?

Recently I was reading "The Definitive Guide to JavaScript (6th Edition)", translated by the Taobao team. See the chapter on arrays to introduce some methods of JS arrays.
pop() push() treats the array as a stack, and then deletes and adds array elements at the end of the array.
unshift() shift() also treats the array as a stack, but it deletes and adds elements at the head of the array.
All four methods will update the length of the array.
But regarding the return value mentioned, I am a little confused after seeing the example given.
Sample code in the book:

var statck=[]; //stack:[]
stack.push(1,2); //stack:[1,2]  返回2
stack.pop();   //stack:[1]      返回2
stack.push(3);  //stack:[1,3]   返回2
stack.pop();    //stack:[1]     返回3
stack.push([4,5]); //stack:[1,[4,5]]   返回2
stack.pop();  //stack:[1]       返回[4,5]
stack.pop(); // stack:[]    返回1

The return value should be the currently deleted or inserted value
The last value inserted in the second line is the value 2, so the return value is 2.
Then why is the code in line 4 above still there? Return value 2? Isn't it the value 3? Because the value inserted is 3.

stack.push(3); //stack:[1,3] 返回2

Then line 6 also does not understand the subsequent return value:

stack.push([4,5]); //stack:[1,[4,5]]   返回2

Why is the returned value 2 instead of 5?

女神的闺蜜爱上我女神的闺蜜爱上我2767 days ago1603

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-06-12 09:27:04

    Array.prototype.pop()
    Return value
    The removed element from the array; undefined if the array is empty.

    Array.prototype.push()
    Return value
    The new length property of the object upon which the method was called.

    Array.prototype.unshift()
    Return value
    The new length property of the object upon which the method was called.

    Array.prototype.shift()
    Return value
    The removed element from the array; undefined if the array is empty.

    That is: push() and unshift() will return the length of the new array, while pop() and shift() will return the removed elements (return undefined when the array is empty) )

    Source: MDN

    reply
    0
  • 迷茫

    迷茫2017-06-12 09:27:04

    1, pusn returns the length of the array.
    2, pop, returns the deleted element.
    3, unshift, returns the length of the array.
    4, shift returns the deleted element.

    reply
    0
  • Cancelreply