This album is based on the video “JavaScript data structures and Algorithms”, the author of this article has the notes, source code, test environment hosted on GitHub, welcome students Star and Fork.

It is recommended that you learn the structure of the directory in order, from the simple to the deep, step by step, easy to figure out the data structure and algorithm.

Almost all programming languages natively support array types because arrays are the simplest in-memory data structures. Arrays are typically used to store a series of values of the same data type. But in JavaScript, arrays can hold different types of values. But let’s follow best practice and don’t do this (most languages don’t have this capability).

Create and initialize an array

  • new Array()

    / / sample
    const daysOfWeek = new Array(
      "Sunday"."Monday"."Tuesday"."Wednesday"."Thursday"."Friday"."Saturday"
    );
    Copy the code
  • []

    / / sample
    const daysOfWeek = [
      "Sunday"."Monday"."Tuesday"."Wednesday"."Thursday"."Friday"."Saturday",];Copy the code

Common operations on arrays

Add elements

  • Add an element to the end of the arrayarray.push(item)
  • Inserts an element at the top of the arrayarray.unshift(item)
  • Inserts an element at the specified index positionarray.splice(index, 0, item)

    Splice () When the second parameter is 0, data is inserted.

    let myArray = [1.2.3];
    // Insert A at index 0
    myArray.splice(0.0."A");
    console.log(myArray); //--> ['A', 1, 2, 3]
    Copy the code

Remove elements

  • Deletes the last element of the arrayarray.pop(item)
  • Removes the first element of the arrayarray.shift(item)
  • Deletes the element at the specified index positionarray.splice(start, number)Such as:
    let myArray2 = [1.2.3.4.5];
    // delete 2 elements from index 4
    myArray2.splice(4.2);
    console.log(myArray2); / / -- > [1, 2, 3]
    Copy the code

Modify the element

  • Modifies the element at the specified index positionarray.splice(index, 1, item)
    let myArray3 = [1.2.3.4.5.6];
    // Change the element at index 1 to AA
    myArray2.splice(1.1."AA");
    console.log(myArray3); //--> [1, "AA", 3, 4, 5, 6]
    Copy the code
  • Modifies several elements at the specified index locationarray.splice(index, number, item)
    let myArray4 = [1.2.3.4.5.6.7];
    // From index 2, change the two elements to AA BB
    myArray2.splice(2.2."AA"."BB");
    console.log(myArray3); //--> [1, 2, "AA", "BB", 5, 6, 7]
    Copy the code

Album series

  • Learn JavaScript data structures and algorithms from 0