Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

JavaScript arrays for stacks and queues

Array Array definition

  1. Definition understanding:

An array is a contiguous memory segment divided equally into length chunks, each of which is associated with an integer. This integer is the index of the array,

  1. The length of the array

    The magic property of the array, length, is not the number of elements in the array, but the highest ordinal number of elements in the array +1.

  2. Array objects inherit from Array.prototype, which has some more practical methods

Array type judgment:

What type is an array? It can be a bit confusing to return ‘object’ when using typeof for judgment.

There’s usually another way to tell if a value is an Array: array.isarray (value)

const array_is_what = new Array(621)
typeof array_is_what // ==> "object"

Array.isArray(array_is_what) // true
// Returns true, an array

Copy the code

Stacks and queues must be understood!

  • Stack: First in last out

  • Queue: First in, first out

Arrays and stacks

Some methods of arrays, when used together, make arrays look like stacks.

The.pop() method returns the last element in the array and removes it from the original array. The.push(value) method adds the value passed to the end of the array

Arrays and queues

The.shift() method, which removes and returns elements with subscript 0 from an array, is similar but opposite to.pop()

The.unshift() method is similar to the.push(value) method, but inserts the element at the beginning of the array

When the.shift() method is used with the.push(value) method,

The array is like a queue.