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?
That is:
push()
andunshift()
will return the length of the new array, whilepop()
andshift()
will return the removed elements (returnundefined
when the array is empty) )Source: MDN
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.