06_JavaScript array

1 First introduction to arrays

How to save the relevant information of all students in a class, such as name, student ID, and age?

  • One method uses the knowledge learned previously, and each piece of information needs a variable to save. The disadvantage is that it is very troublesome, error-prone, and unreasonable.
  • Another way is to use arrays.

An array is a collection of variables that stores a series of values.

Array composition: The array consists of one or more array elements, and each element is separated by commas ",".

Array elements: Each array element consists of "subscript" and "value".

  • Subscript: also called index, represented by a number, starting from 0 by default and increasing in sequence, used to identify elements.
  • Value: The content of the element, which can be any type of data, such as numeric type, character type, array, object, etc.

Arrays can also be divided into multi-dimensional arrays such as one-dimensional arrays, two-dimensional arrays, and three-dimensional arrays based on the number of dimensions.

  • One-dimensional array: It means that the "value" of the array is non-array type data, as shown in the figure above.

  • Two-dimensional array: means that the "value" of the array element is a one-dimensional array, as shown below.

  • Multidimensional array: When the value of an array is also an array, a multidimensional array can be formed. It is usually used to describe some information.

Save a class's student information. Each array element represents a student, and each student uses a one-dimensional array to represent his or her name, student number, age and other information. In this way, a class's information can be saved regularly through a variable. All student information is convenient for processing during development.

2 Create an array

How arrays are created in JavaScript:

  • The way to instantiate an Array object is new Array().
  • Use "[]" directly.

2.1 Create array using Array object

Creating an array by instantiating an Array object is achieved through the new keyword.

// 元素值类型为字符串
var area = new Array('Beijing', 'Shanghai', 'Shenzhen');
// 元素值类型为数值型
var score = new Array(56, 68, 98, 44);
// 元素值类型为混合型
var mix = new Array(123, 'abc', null, true, undefined);
// 空数组
var arr1 = new Array();
var arr2 = new Array;

2.2 Use "[]" to create an array

The direct method "[]" is used in a similar way to the Array() object, just replace new Array() with [].

var weather = ['wind', 'fine',]; // 相当于:new Array('wind', 'fine',)
var empty = [];                  // 相当于:new Array
// 控制台输出 mood:(5) ["sad", empty × 3, "happy"]
var mood = ['sad', , , ,'happy'];   
  • When creating an array, the comma after the last element can be present or omitted.
  • The difference between the direct method "[]" and the Array() object when creating arrays is that the former can create arrays with empty storage locations, while the latter cannot.
  • When there is only one parameter, the results will be different.
var arr = [10];  //创建一个第一个值为10的数组
var arr1 = new Array(10);  //创建一个长度为10的数组
console.log(arr);
console.log(arr1);

3 Basic operations on arrays

3.1 Get the array length

The length property provided by the Array object can obtain the length of the array, and its value is the maximum subscript of the array element plus 1.

var arr1 = [78, 88, 98];
var arr2 = ['a', , , , 'b', 'c'];
console.log(arr1.length); // 输出结果为:3
console.log(arr2.length); // 输出结果为:6
  • Array elements with no values ​​in array arr2 occupy empty storage locations. Therefore, the array subscript will still be incremented. Therefore, the final output result of arr2 calling the length attribute is 6.

The length property of an array can not only be used to obtain the length of the array, but also modify the length of the array.

When using the length attribute to specify the length of an array, there are three situations:

  • The set length > the original array length. If the value of length is greater than the original number of elements in the array, array elements without values ​​will occupy empty storage locations.
var arr1 = [];
arr1.length = 5;
console.log(arr1);      // 输出结果:(5) [empty × 5]
var arr2 = [1, 2, 3];
arr2.length = 4; 
console.log(arr2);      // 输出结果:(4) [1, 2, 3, empty]
  • The set length = the length of the original array. If the value of length is equal to the original number of elements in the array, the length of the array remains unchanged.
var arr3 = ['a', 'b'];
arr3.length = 2; 
console.log(arr3);      // 输出结果:(2) ["a", "b"]
  • The set length<original array length. If the value of length is less than the original number of elements in the array, the excess array elements will be discarded.
var arr4 = ['hehe', 'xixi', 'gugu', 'jiujiu'];
arr4.length = 3; 
console.log(arr4);      // 输出结果:(3) ["hehe", "xixi", "gugu"]

In addition, when creating an array using the Array object method, you can also specify the length of the array.

var arr = new Array(3);
console.log(arr);      // 输出结果:(3) [empty × 3]

Note: No matter how you specify the array length in JavaScript, it does not affect the continued addition of elements to the array, and the length attribute value of the array will change accordingly.

3.2 Array access and traversal

Access array elements

Array element access method: "array name [subscript]".

var fruit = ['苹果', '香蕉', '橘子'];
console.log(fruit[0]);
console.log(fruit[1]);
console.log(fruit[2]);
console.log(fruit[3]);

When accessing data that does not exist in the array, undefined will be returned instead of an error.

Iterate over array elements

The so-called traversal of an array is the operation of sequentially accessing all elements in the array.

  • To traverse an array using subscripts, you can use for (loop statement).
  • To traverse an array using subscripts, you can use the for...in statement.
for (variable in object) {
    
    ...}
  • The variable in for...in refers to the array subscript.
  • The object in for...in represents the variable name of the array.
  • In addition, if object is an object, for...in can also be used for object traversal.
var arr = [12, 59, 66];    // 待求和的二维数组
var sum = 0;
for (var j in arr) {
    
        // 遍历数组arr的元素
    sum += arr[j];        // 二维数组元素累计相加
}
ES6’s new for…of syntax

In ES6, a new for...of syntax is added to make it easier to traverse arrays.

var arr = [1, 2, 3];
for (var value of arr) {
    
    
   console.log(value);
}
  • Variable value: represents the value of the corresponding array element each time it is traversed.
  • Variable arr: represents the array to be traversed.
  • Result: 1, 2, and 3 are output in the console.
forEach traverses the array
  • Iterate through the entire array in order
  • Supports IE8 or above or other browsers
  • A function created by yourself but not called by yourself is called a callback function

grammar:

Array.forEach(function(value, index, arr){
    
     ... });
var arr = [2, 3, 4, 5, 6, 7]; 
arr.forEach(function(item, index, arr){
    
    
    //三个参数分别代表 item 当前遍历到的元素 index 当前遍历到的下标 arr 数组本身 
})

3.3 Addition and modification of elements

The method of adding and modifying elements: "array name [subscript]". The same way you access elements in an array.

Add element
var height = [];
height[5] =  183;
height[0] =  175;
height[3] =  150;
console.log(height);
  • Add array elements: array name [subscript] = value.
  • Subscripts are allowed to be added consecutively in non-numeric order, and elements with no specific value set will exist as empty storage locations.
  • The order in which the elements are saved in the array is related to the subscript and has nothing to do with the order in which elements are added.
var arr = ['Asa','Taylor'];
arr[2] = 'Tom';
arr[3] =  'Jack';
console.log(arr);
Modify elements

Modifying elements is used in the same way as adding elements. The difference is that modifying elements reassigns values ​​to elements that already contain values.

var arr = ['a', 'b', 'c', 'd'];
arr[2] = 123;
arr[3] = 456;
console.log(arr);	

3.4 Deletion of elements

After creating an array, sometimes it is necessary to delete an element value in the array according to the actual situation.

For example, a multidimensional array that stores student information for the entire class. If a student in this class transfers to another school, the student needs to be deleted from the array that stores student information.

At this time, you can use the delete keyword to delete the value of the array element.

The delete keyword can only delete the element value of the specified subscript in the array. After deletion, the element will still occupy an empty storage location.

var stu = ['Tom', 'Jimmy', 'Lucy'];
console.log(stu);	// 输出结果:(3) ["Tom", "Jimmy", "Lucy"]
delete stu[1];	// 删除数组中第2个元素
console.log(stu);	// 输出结果:(3) ["Tom", empty, "Lucy"]

3.5 Destructuring assignment

In addition to the variable declaration and assignment methods learned previously, ES6 also provides another method - destructuring assignment.

For example, if the elements in the array [1,2,3] are assigned to a, b, and c respectively, the traditional approach is to declare and assign values ​​to the variables separately.

// 传统的做法
var arr = [1, 2, 3];
var a = arr[0];
var b = arr[1];
var c = arr[2];

// 解构赋值方式
[a, b, c] = [1, 2, 3];
  • When the number of variables on the left is less than the number of elements on the right, the excess elements are ignored.
  • When the number of variables on the left is greater than the number of elements on the right, the excess variables will be initialized to undefined.
var arr = [1, 2, 3];
[a, b] = arr;
// 输出结果:1 - 2
console.log(a + ' - ' + b);   

var n1 = 4, n2 = 8;
[n1, n2] = [n2, n1];
// 输出结果:8 - 4
console.log(n1 + ' - ' + n2); 
  • When destructuring assignment, the content on the right side can also be a variable.
  • The exchange of values ​​of two variables is completed through destructuring assignment.

3.6 Practice assignments

  • Find the maximum and minimum values, enter the scores of 5 subjects, and find the total score, average score, highest score, and lowest score
    • Assume that the first element of the array to be searched is the maximum value max and the minimum value min.
    • Iterate over the array starting from the second element of the array.
    • When traversing the array, determine whether the current element is greater than max, and if so, modify the max value.
    • In the same way, when traversing the array, determine whether the current element is less than min, and if it is less, modify the min value.
  • Returns the index of the specified element in the array

4 Common two-dimensional array operations

4.1 Creation and traversal

After understanding how to create a one-dimensional array, creating a two-dimensional array is very simple. You only need to set the array elements to an array.

// 使用Array对象创建数组
var info = new Array(new Array('Tom', 13, 155), new Array('Lucy', 11, 152));
var arr = new Array(new Array, new Array);// 空二维数组
// 使用“[]”创建数组
var num = [[1, 3], [2, 4]];
var empty = [[], []];		            // 空二维数组

After creating a two-dimensional array, how to traverse the elements in the two-dimensional array and operate on them?

  • One-dimensional arrays can be traversed using for, for...in or for...of (provided by ES6).
  • For a two-dimensional array, you only need to traverse the elements of the array again after traversing the array.

In web project development, multi-dimensional arrays are often created by adding elements to multi-dimensional empty arrays.

var arr = [];	   // 创建一维空数组
for(var i = 0 ; i< 3; ++i){
    
    
    arr[i] = []; 	  // 将当前元素设置为数组
    arr[i][0] = i;	  // 为二维数组元素赋值
}

Notice:

  • If you want to assign a value to a two-dimensional array element ( 如arr[i][0]), you must first ensure that the added element (such as arr[i]) has been created as an array, otherwise the program will report an "Uncaught TypeError..." error.
  • When creating a multi-dimensional array, although JavaScript does not limit the number of array dimensions, in actual applications, in order to facilitate code reading, debugging, and maintenance, it is recommended to use three-dimensional or less arrays to save data.

4.2 Practice assignments

  • Transpose a two-dimensional array

    • The transposition of a two-dimensional array refers to saving the horizontal elements of the two-dimensional array into vertical elements.

    • res[0][0] = arr[0][0]、res[0][1] = arr[1][0]、res[0][2] = arr[2][0]

    • res[i][j] = arr[j][i]

    • The length of the res array = the length of the arr element (such as arr[0]).

    • The length of the res element (such as res[0]) = the length of the arr array.

5 Array sorting

5.1 Bubble sort

Bubble sort: It is a simpler sorting algorithm in the field of computer science.

Implementation principle: In the process of bubble sorting, sort from small to large or from large to small as required, continuously compare the values ​​of two adjacent elements in the array, and move the smaller or larger element forward.

  • Compare adjacent elements. If the first one is bigger than the second one, swap them both.

  • Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. At this point, the last element should be the largest number.

  • Repeat the above steps for all elements except the last one.

  • Keep repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.

Number of rounds of comparison = array length - 1;

Number of comparisons per round = array length - current number of rounds

// 编写方法,实现冒泡
var arr = [98, 31, 5, 27, 2, 78];
//外层循环,控制趟数,每一次找到一个最大值
for (var i = 0; i < arr.length - 1; i++) {
    
    
    // 内层循环,控制比较的次数,并且判断两个数的大小
    for (var j = 0; j < arr.length - (i + 1); j++) {
    
    
        // 白话解释:如果前面的数大,放到后面(当然是从小到大的冒泡排序)
        if (arr[j] > arr[j + 1]) {
    
    
            var temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
        }
    }

}
console.log(arr);

5.2 Insertion sort

Insertion sort: It is also an optimization of bubble sort and is an intuitive and simple sorting algorithm.

Implementation principle: By constructing the storage of ordered array elements, for unsorted array elements, traverse from the last element to the first element in the sorted array, find the corresponding position and insert it. Among them, the first element of the array to be sorted will be regarded as an ordered array, and the second to the last element will be regarded as an unordered array.

  • Starting from the first element, the element can be considered to have been sorted;
  • Take out the next element and scan from back to front in the sorted element sequence;
  • If the element (sorted) is larger than the new element, move the element to the next position;
  • Repeat step 3 until you find a position where the sorted element is less than or equal to the new element;
  • After inserting the new element at that position;
  • Repeat steps 2~5.
let arr = [98, 7, 65, 54, 12, 6];
let len = arr.length;
let preIndex, current;
for (let i = 1; i < len; i++) {
    
    
    preIndex = i - 1;
    current = arr[i];
    while (preIndex >= 0 && current < arr[preIndex]) {
    
    
        arr[preIndex + 1] = arr[preIndex];
        preIndex--;
    }
    arr[preIndex + 1] = current;
}
return arr;

For example: Sort from small to large. The number of insertion sort comparisons is equal to the length of the unsorted array.

6 common array methods

6.1 Stack and queue methods

In JavaScript, in addition to the previously explained methods of adding and deleting array elements, you can also use the methods provided by the Array object to simulate stack and queue operations.

  • Appends a new element of an array at the end or beginning of the array.
  • Remove array elements from the end or beginning of the array.
method name Function description Format
push() Appends one or more elements to the end of an array and returns the array's new length. Array.push(parameter 1, parameter 2...);
unshift() Adds one or more elements to the beginning of the array and returns the array's new length. Array.unshift(parameter1,parameter2…);
pop() Removes and returns an element from the end of the array, or undefined if the array is empty. Array.pop();
shift() Removes and returns an element from the beginning of the array, or undefined if the array is empty. Array.shift();
  • The return value of the push() and unshift() methods is the length of the new array.
  • The pop() and shift() methods return the shifted array element.

6.2 Search method

In development, you want to detect whether a given value is an array, or to find the position of a specified element in an array.

method name Function description Format
includes() Used to determine whether an array contains an element, returns true if it does, otherwise returns false. Array.includes(searchvalue, start);
Array.isArray() Used to determine whether the passed value is an Array, whether it returns true or not returns false.
indexOf() Returns the first index in the array where the given value can be found, or -1 if it does not exist Array.indexOf(searchvalue,start);
lastIndexOf() Returns the index of the last element in the array, or -1 if it does not exist Array.indexOf(searchvalue,start);

Except for the Array.isArray() method, all other methods in the table start retrieval from the specified array index by default, and the retrieval method is the same as the operator "===", that is, only when they are congruent will a more successful result be returned. .

includes() and Array.isArray() methods
var data = ['peach', 'pear', 26, '26', 'grape'];
// 从数组下标为3的位置开始检索数字26
console.log(data.includes(26, 3));       // 输出结果:false
// 从数组下标为data.length - 3 的位置查找数字26
console.log(data.includes(26, -3));      // 输出结果:true
// 判断变量data是否为数组
console.log(Array.isArray(data));        // 输出结果:true
  • The first parameter of the includes() method represents the value to be found.
  • The second parameter of the includes() method is used to specify the starting position of the subscript to be searched in the array.
    • When set to greater than the length of the array, the array will not be retrieved and false will be returned directly.
    • When set to a number less than 0, the index position retrieved is equal to the length of the array plus the specified negative number. If the result is still a number less than 0, the entire array is retrieved.
indexOf() method

indexOf() is used to retrieve the first given value from the specified subscript position in the array. If it exists, it returns the corresponding element subscript, otherwise it returns -1.

The second parameter of the indexOf() method is used to specify the index to start searching:

  • When its value is greater than or equal to the length of the array, -1 is returned directly.
  • When its value is a negative number, the search subscript position is equal to the length of the array plus the specified negative number. If the result is still a number less than 0, the entire array is retrieved.
var fruits = ["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
var a = fruits.indexOf("Apple",4);
lastIndexOf() method

The lastIndexOf() method provided by the Array object is used to retrieve the index of the last given value in the array from the specified index position. Different from the indexOf() retrieval method, the lastIndexOf() method defaults to reverse retrieval, that is, retrieval from the end of the array to the beginning of the array.

The second parameter of the lastIndexOf() method is used to specify the search index, and because it is retrieved in reverse:

  • When its value is greater than or equal to the array length, the entire array will be searched.
  • When its value is a negative number, the index position is equal to the length of the array plus the given negative number. If its value is still a negative number, -1 is returned directly.
var fruits = ["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
var a = fruits.lastIndexOf("Apple",4);

6.3 Convert array to string

If you need to convert an array into a string during development, you can use the methods provided by JavaScript to achieve this.

method name Function description Format
join() Concatenates all elements of an array into a string. Array.join(string);
toString() Returns a string representing the specified array and its elements. Array.toString();
var arr = ['a','b','c'];
console.log(arr.join());      // 输出结果:a,b,c
console.log(arr.join('-'));   // 输出结果:a-b-c
console.log(arr.toString());  // 输出结果:a,b,c

Similarities between join() and toString() methods:

  • Multidimensional arrays can be converted to strings, using comma concatenation by default.
  • When an array element is undefined, null or an empty array, the corresponding element will be converted to an empty string.

The difference between join() and toString() methods:

  • The join() method can specify the symbol for joining array elements.

6.4 Other methods

In addition to the several common methods explained earlier, JavaScript also provides many other commonly used array methods.

For example, merge arrays, shallow copy arrays, reverse the order of array elements, etc.

method name Function description Format
sort() Sorts the elements of an array and returns the array. array.sort([callback function]);
fill() Fills all elements in the array with a fixed value within the specified index range array.fill(value, start, end);
reverse() Reverse the position of elements in an array array.reverse();
splice() Delete or add elements to an array within a specified range of subscripts array.splice(start, number[,element 1, element 2…]);
slice() Copies array elements from an array within a specified index range to a new array array.slice(start, end);
concat() Returns a new array merged from two or more arrays array.concat(any data type [, any data type...]);
  • The slice() and concat() methods return a new array after execution and will not affect the original array. The remaining methods will affect the original array after execution.
  • When the value of the first parameter of the splice() method is equal to or greater than the length of the array, the operation starts from the end of the array; when the value is a negative number, the subscript position is equal to the length of the array plus the specified negative number, if the value is still a negative number , then the operation starts from the beginning of the array.
/* array.sort([回调函数]);
** 给数组中的元素排序,默认以 unicode 编码顺序排列,因此直接对数组中的数字排序会产生预料外的结果
** 可以传递一个回调函数作为sort的参数,回调函数中有两个形参分别表示数组中一前一后的两个元素,具体是哪两个元素需要根据循环确认
** 函数的返回值决定是否交换这个两个元素
** -- 当返回值大于0时交换
** -- 小于0时不交换
** -- 等于0时认为两个值相等不交换
** 会直接修改原数组的元素,与方法的返回值相同
*/
var arr = [1, 10, 20, 15, 25, 5];
arr.sort(function(a, b){
    
    
    return a-b;
});

/* arr.reverse();
** 第一个参数是截取开始的索引,返回数组会包括开始索引的元素
** 第二个参数是截取结束的索引,返回数组不会包括结束索引的元素
** 参数可以是负值,如果为负就是从后往前计数
*/
var arr = [1,2,3,4];
var result = arr.reverse()
console.log(result); // 4,3,2,1
console.log(arr);    // 4,3,2,1

/* array.slice(start, end);
** 第一个参数是截取开始的索引,返回数组会包括开始索引的元素
** 第二个参数是截取结束的索引,返回数组不会包括结束索引的元素
** 参数可以是负值,如果为负就是从后往前计数
*/
var arr = [0,1,2,3,4,5];
var arr1 = arr.slice(0,4);
console.log(arr1);
var arr2 = arr.slice(-3,-1);
console.log(arr2);

/* array.splice(start, number[,元素1, 元素2...]);
** 第一个参数为从哪个索引开始删除元素
** 第二个参数为删除几个元素
** 从第三个参数开始的参数都是是在第一个参数的索引之前添加这些元素
*/
var arr = [0,1,2,3,4,5];
arr.splice(0,1,7,8,9);
console.log(arr);

/* array.concat(任意数据类型[,任意数据类型...]);
** 可以将两个或者多个数组连接成一个数组,不会改变原数组
** 拷贝原数组,生成原数组
*/
var arr = [1,2,3,4];
var result = arr.concat([5,6,7,8],1,"a", false, null, undefined, {
    
    });
console.log(result);

7 Practice Assignments

  • Using bubble sort, sort from large to small, the array is 70,35,67,49,20,59,98,100

  • Find the length of each item in a string array

  • Output the number of data in any two-dimensional array

  • Split a string array with | or other symbols

  • Array deduplication

  • There is an array sorted from small to large. Now enter a number and insert it into the array according to the original rules.

  • Monkey chooses the king

    • A group of monkeys are asked to line up in a circle and number them sequentially according to "1,2,...,n". Then start counting from the 1st monkey, count to the mth monkey, and kick it out of the circle. The following monkeys will start counting from 1, count to the mth monkey, kick it out... and so on. , until there is only one monkey left, and that monkey is the king we are looking for.

      • Assume n (total number of monkeys): 8, m (those kicked out of the circle): 3

      • First round: The kicked monkeys are numbered 3 and 6, and the position numbers are 3 and 6.

      • Second round: The kicked monkeys are numbered 1 and 5, and the position numbers are 9 and 12.

      • Third round: The kicked monkeys are numbered 2 and 8, and the position numbers are 15 and 18.

      • Circle 4: None.

      • Round 5: The kicked monkey is numbered 4 and the position number is 21.

      • The monkey king number is obtained: 7.

      • Receive the total number of monkeys n passed by the user and the mth monkey kicked out through prompt().

    • Use an array to save the numbers of all monkeys (1~n).

    • Set a variable i to record the position of the monkey participating in the game (counting) each time.

    • Through the while loop, as long as the number of elements in the monkey array is greater than 1, the loop will continue.

    • In the loop, determine whether the remainder of the current monkey's positions i and m is 0. If it is zero, delete the array element.

  • Three-level linkage between provinces and cities

    • In web development, regional linkage is a very common function.
    • For example, shopping, takeout, etc. require you to choose a delivery address.
    • Among them, the three-level linkage of provinces and cities is the most basic function.
    • Next, use arrays to save relevant province, city and region information.
    • The one-dimensional array provinces stores provinces, autonomous regions and municipalities.
    • The two-dimensional array cities stores all the cities under the corresponding provinces, autonomous regions, and municipalities. When storing, ensure that the index value in cities[index] is the same as the subscript index of the element in the corresponding provinces.
    • In the same way, use a three-dimensional array to save all areas under each city.

This continues until there is only one monkey left, and that monkey is the king we are looking for.
- Suppose n (total number of monkeys): 8, m (those kicked out of the circle): 3
- In the first circle: the monkeys kicked out are numbered 3 and 6, and the position numbers are 3 and 6.
- Second circle: The kicked monkeys are numbered 1 and 5, and the position numbers are 9 and 12.
- The third circle: The kicked monkeys are numbered 2 and 8, and the position numbers are 15 and 18.
- Circle 4: None.
- The fifth circle: The kicked monkey number is 4 and the position number is 21.
- The number of the Monkey King is obtained: 7.

- 通过prompt()接收用户传递的猴子总数n和踢出的第m只猴子。
  • Use an array to save the numbers of all monkeys (1~n).

  • Set a variable i to record the position of the monkey participating in the game (counting) each time.

  • Through the while loop, as long as the number of elements in the monkey array is greater than 1, the loop will continue.

  • In the loop, determine whether the remainder of the current monkey's positions i and m is 0. If it is zero, delete the array element.

  • Three-level linkage between provinces and cities

    • In web development, regional linkage is a very common function.
    • For example, shopping, takeout, etc. require you to choose a delivery address.
    • Among them, the three-level linkage of provinces and cities is the most basic function.
    • Next, use arrays to save relevant province, city and region information.
    • The one-dimensional array provinces stores provinces, autonomous regions and municipalities.
    • The two-dimensional array cities stores all the cities under the corresponding provinces, autonomous regions, and municipalities. When storing, ensure that the index value in cities[index] is the same as the subscript index of the element in the corresponding provinces.
    • In the same way, use a three-dimensional array to save all areas under each city.

Guess you like

Origin blog.csdn.net/zhangchen124/article/details/133277139