What is the return value after pop() push() unshift() shift() operates on an array in Javascript?
女神的闺蜜爱上我
女神的闺蜜爱上我 2017-06-12 09:25:04
0
2
1489

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?

女神的闺蜜爱上我
女神的闺蜜爱上我

reply all (2)
洪涛

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()andunshift()will return the length of the new array, whilepop()andshift()will return the removed elements (returnundefinedwhen 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.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!