What is an array?

The standard definition of an array is that it is a linear collection of elements that can be accessed arbitrarily by an index, usually a number, that calculates the offset of the stored location of the element. If you’ve read about other languages, you know that all programming languages have similar data structures. But javascript arrays are different from other languages. An array in JavaScript is a special kind of object whose index is the primality of the object. The index may be an integer. However, these numeric indexes are converted to string type internally, because the attribute names of JavaScript objects must be strings. Arrays are just special objects in JavaScript, so they are not as efficient as arrays in other languages. Arrays in JavaScript, technically called objects, are special JavaScript objects that are internally classified as arrays. Because Array is treated as an object in JavaScript, it has a number of properties and methods that can be used programmatically.

2. Use arrays

JavaScript arrays are very flexible and there are a lot of ways to manipulate arrays, but you need to create them before you can use them.

2.1 Creating an Array

Method 1: Declare an array variable with the [] operator

var nums = []
Copy the code

An array created this way yields an empty array of length 0, which can be verified by the array’s length property

var nums = [1.2.3.4.5]
Copy the code

You can also put in a list of elements by declaring an array in the [] operator

Method 2: Create an Array by calling the Array constructor

 let nums = new Array(a);console.log(nums.length)  / / 0
Copy the code

You can also set the initial value when declaring:

 let nums = new Array(1.2.3.4.5);
 console.log(nums.length)   / / 5
Copy the code

When we call the Array constructor, we can pass in a single argument that specifies the length of the Array:

 let nums = new Array(20);
 console.log(nums.length)   / / 20
Copy the code

2.2 Reading and Writing an Array

    let arr = []  / / declare
    let sums = 0
    for (let i = 0; i < 100; i++) {   / / assignment
        arr[i] = i
    }
    arr.map((item, i) = > {  / / read
        // console.log(item,i);
        sums += item
    })
    console.log(sums);   / / 4950
Copy the code

2.2.1 Generating arrays from strings

Calling the split() method of a string object can also generate an array:

let str=`we are family ! `
    let arr=str.split("")
    arr.map((item,i) = >{
        console.log(`arr${i}:${item}`);
        Arr0 :we arr1:are arr2:family arr3:! * /
    })
Copy the code

2.2.2 Global operation on arrays

Is done with the array as a whole. For example, global assignment:

    let arr = []  / / declare
    for (let i = 0; i < 10; i++) {   / / assignment
        arr[i] = i
    }
    let arr2 = arr
Copy the code

However, assigning from one array to another in this way simply adds a new reference to the assigned array. When you modify the value of an array with the original reference, another reference will also sense the change, as in:

 let arr = []  / / declare
    for (let i = 0; i < 10; i++) {   / / assignment
        arr[i] = i
    }
    let arr2 = arr
    arr[0] =100
    console.log(arr1[0])  / / 100
Copy the code

This behavior is called shallow copying, where the new array still points to the original array. A better solution is to use deep copy, where each element in the original array is copied into the new array. For example, we can write a function to deeply copy an array:

    let arr1=[0.1.2.3.4.5.6.7.8.9],arr2=[]
    function CopyArr(arr1,arr2){
        arr1.map((item,i) = >{
            arr2[i]=item
        })
        return arr2
    }
    arr2=CopyArr(arr1,arr2)
    console.log(arr2);     // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    arr1[0] =100
    console.log(arr1[0],arr2[0]);  //100 0
Copy the code

2.3 Array Methods

1. The JavaScript method toString() converts an array to a comma-separated string of array values.

2. The join() method also combines all array elements into a single string.

The pop() method removes the last element from the array.

The push() method (at the end of the array) adds a new element to the array.

5. The shift() method removes the first array element and “shifts” all other elements to lower indexes.

6. The unshift() method (at the beginning) adds a new element to the array and “reverses” the old element.

The length attribute provides an easy way to append new elements to an array.

8. Using delete leaves an undefined void in the array. Use pop() or shift() instead.

9. The splice() method can be used to add new items to an array, or to remove elements from an array.

The concat() method creates a new array by merging (concatenating) existing arrays.

The slice() method slices a new array with a fragment of the array.

12. The sort() method is used to sort the elements of an array.

13. The reverse() method is used to reverse the order of elements in an array.

The toLocaleString() method converts an array to a local string.

15. The valueOf() method returns the original Array value.

Specific usage: www.w3school.com.cn/jsref/jsref…

2.4 Two-dimensional and multidimensional arrays

JavaScript only supports one-dimensional arrays, but you can easily create multi-dimensional arrays by storing array elements inside them.

2.4.1 Creating a TWO-DIMENSIONAL array

A two-dimensional array is like a table of rows and columns. To create a two-dimensional array in JavaScript, you first create an array and then make each element of the array an array. We need to know how many rows a two-dimensional array should contain. With this information, we can create a two-dimensional array with n rows and 1 column:

   let arr=[]
   let rows=5
   for(let i=0; i<rows; i++){ arr[i]=[] }console.log(arr);   // [Array(0), Array(0), Array(0), Array(0), Array(0)]
Copy the code

The problem with this is that every element in the array is undefined. A better approach is to follow The example on page 64 of JavaScript: The Good Parts (O’Reilly), where Crockford extends The JavaScript array object by adding a new method that sets The number of rows, columns, and initial values of The array based on The parameters passed in. Here is the definition of this method:

/* @params numrows: number of rows numcols: number of columns Initial: number of rows */
    Array.matrix = function (numrows, numcols, initial) {
        let arr = []
        for (let i = 0; i < numrows; i++) {
            let columns = []
            for (let j; j < numcols; j++) {
                columns[j] = initial
            }
            arr[i] = columns
        }
        return arr
    }
    
    let nums = Array.matrix(5.5.0);
    console.log(nums[0] [0])    / / 0
Copy the code

For small amounts of data it is easiest to use this method, which only requires one line of code:

 let nums = [[1.2.3], [4.5.6], [7.8.9]]
 console.log(nums[2] [2]);   / / 9
Copy the code

2.4.2 Handling elements of two-dimensional arrays

There are two basic ways to handle elements in a two-dimensional array: column access and row access:

    let nums = [[1.2.3], [4.5.6], [7.8.9]]
    let total = 0
    for (let i = 0; i < nums.length; i++) {
        for (let j = 0; j < nums[i].length; j++) {
            total += nums[i][j]
        }
    }
    console.log(total) 
Copy the code

For a multidimensional array, the inner loop controls the rows, and the outer loop controls the columns.

2.5 Arrays in objects

In objects, arrays can be used to store complex data.

    function wageTemp() {
        this.dataSource = []
        this.add = add
        this.averag = averag
    }
    function add(data) {
        this.dataSource.push(data)
    }
    function averag() {
        let total = 0
        this.dataSource.map(item= > {
            total += item
        })
        return total / this.dataSource.length
    }

    let gzTemp = new wageTemp()
    gzTemp.add(100)
    gzTemp.add(90)
    gzTemp.add(80)
    gzTemp.add(88)
    gzTemp.add(99)
    console.log(gzTemp.averag());    / / 91.4

Copy the code

(The above content is the summary note of reading “JavaScript Description of Data Structures and Algorithms”, if there is any similarity, it is purely coincidence…)