I am having hard time remembering what Array.shift() and Array.unshift() do.

After few years, I still have too check out reference from time to time when I need to use one of them. Can anyone explain why those names are choosen and how to memorize which one does what?

I have no such problem with Array.push() and Array.pop()

有帮助吗?

解决方案 4

This is certainly the most confusing pair of function names. The only salvation I can offer is to remember one of the following two things:

  • Shift can be thought of as "moving something around," and perhaps you can picture that if you "shift" an array around a bunch, something is liable to fall off the end (or in this case, the beginning). Unshift puts things back the way they were.
  • It's the opposite of what it sounds like it should be. unshift sounds like undoing something, but in fact, it's putting something onto the array.

Good luck!

其他提示

As I known.

The shift command is come from the binary bit shift [1]. for Example.

    001100
0 < 011000 // when you shift left
|
Yay!

I think it is quite simple it is just like you push it from behind. So this makes sense for me.

The unshift is the opposite way of shift.

    001100
1 > 001100 // they called it unshift
    1001100
    |
    Yay!

So that's it, Hope this helps!

[1] http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts

Just think of your keyboard:

Shift gets a capital version of the first key you press.

.shift() gets the first item off the array.

a.push(e) pushes e onto the end of a.

e = a.pop() pops the last element from a, to e.

a.unshift(e) enqueues e to the start of a.

e = a.shift() gets the first element from a to e.

Use push and pop for stacks.

Use unshift and pop for queues. (Or push and shift)

I remember the difference between shift (destructive) and unshift (constructive) simply by remembering that I use un-shift for en-queueing, and shift is the opposite to unshift.

How about:

SHIFTer makes a drifter

It returns the first entry to the variable.

and -

UNSHIFTer is a weenier that sneaks in line

Inserts argument as first entry in array

Oh, there are deep psychological techniques at work here!! :-o But seriously, you will remember it for its peculiarity :-)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top