js I guess you just can’t remember pop, push, unshift, shift

Code farmers who have manipulated arrays should all know the four methods of pop, push, unshift, and shift.
Sometimes, they just can’t remember who these four methods are.


The following recommends my memory association for these 4 methods

  • push: push, imagine a magazine, push the bullet into the magazine, the new bullet is in the last item of the magazine
  • pop: The gunshot, because the magazine is a stack structure, the bullet comes in first, so the last bullet is obtained when the shot (pop) is shot, and the last item is deleted from the "magazine"
  • shift: Shift, imagine queuing shifts, queuing is a queue structure, first-in-first-out, when it is the next turn (shift), the first one leaves, the next one goes forward
  • unshift: Cancel the shift, which is the opposite of shift, cancel the shift (unshift) instruction, and return to the first place in the queue after leaving, and the next one

If you have a better memory method, or you can leave your method for more people to learn



pop, push, unshift, shift 通用 demo

var arr = [5, 8, 4, 3, 9, 1]

// pop(): 删除最后项, 返回被删的项
console.log(arr.pop()) // 1
console.log(arr) // [5, 8, 4, 3, 9]

// push(item): 最后增加一项, 返回数组新长度
console.log(arr.push(5)) // 6
console.log(arr) // [5, 8, 4, 3, 9, 5]

// unshift(item): 最前增加一项, 返回数组新长度
console.log(arr.unshift(1)) // 7
console.log(arr) // [1, 5, 8, 4, 3, 9, 5]

// shift(): 删除最前项, 返回被删的项
console.log(arr.shift()) // 1
console.log(arr) // [5, 8, 4, 3, 9, 5]

end

Guess you like

Origin blog.csdn.net/u013970232/article/details/110428355