Js one-dimensional array, multi-dimensional array and Object Mixed use method, js dimension

Source: Internet
Author: User

Js one-dimensional array, multi-dimensional array and Object Mixed use method, js dimension

The main purpose of this article is to explain the mixed use of JavaScript arrays and objects. Due to the weak check feature of JS, different types of variables can be stored in the JS array at the same time, for example, you can place numbers, strings, characters, objects, and other content in the same array. Objects can also do the same thing. The difference is that an object can specify the alias of each member of an object, which makes data easier to read during programming. For example:

Var arr1 = ["Flying Fish", 25,172, "Jiangsu"]; var person = {name: "Flying Fish", age: 25, height: 172, province: "Jiangsu "};

In this way, is person. name easier to read and use than arr1 [0? Of course, arrays and objects have their own advantages. The focus of this article is to combine these advantages for comprehensive use.

One-dimensional array
The following code creates an array named cars: Create an array first, and assign values one by one

var cars=new Array();cars[0]="Audi";cars[1]="BMW";cars[2]="Volvo";

Or (condensed array): assign a value when creating an array object.
Copy codeThe Code is as follows:
Var cars = new Array ("Audi", "BMW", "Volvo ");

Or (literal array): it can be used directly without creating variables. However, note that the parentheses () are used to create an object. Instead, brackets ([]) are used to directly assign values. this error is easy if you are not careful.
Instance
Copy codeThe Code is as follows:
Var cars = ["Audi", "BMW", "Volvo"];

The preceding three methods are used to create a one-dimensional array. Due to the weak check of JS, you can put different types of variables in one-dimensional arrays.

2d and multidimensional arrays:
1. Create a two-dimensional array method 1: first create a one-dimensional array, and then all the members of the one-dimensional array create one-dimensional data

var persons = new Array();persons[0] = new Array();persons[1] = new Array();persons[2] = new Array();persons[0][0] = "zhangsan";persons[0][1] = 25;persons[1][0] = "lisi";persons[1][1] = 22;persons[2][0] = "wangwu";persons[2][1] = 32;persons[0] = ["zhangsan", 25];persons[1] = ["lisi", 21];persons[2] = ["wangwu", 32];

Compared with the previous method, this method is easier to read.
Copy codeThe Code is as follows:
Persons. length = 3

2. Create a two-dimensional array method 2: first create a one-dimensional array, and then assign values to all members of the one-dimensional array.
Copy codeThe Code is as follows:
Var persons = new Array ();

3. Create a two-dimensional array. Method 3: assign values directly.
Copy codeThe Code is as follows:
Var persons = [["zhangsan", 25], ["lisi", 21], ["wangwu", 32];

4. Summary
Although the first and second methods are troublesome, you can create an empty multi-dimensional array first, and then assign values according to your needs in the for loop. The third method is easy to use for enumeration data.
The last question of a two-dimensional array is the length of a two-dimensional array or multi-dimensional array? Let's test the following code:
Copy codeThe Code is as follows:
Document. write ("persons =" + persons + "<br/> persons. length =" + persons. length );

The output result is:
Persons = zhangsan, 25, lisi, 21, wangwu, 32
That is to say, the length attribute of a multi-dimensional array returns the length of the first dimension of the multi-dimensional array, rather than the number of elements in the multi-dimensional array.

5. How to return the number of elements in a multi-dimensional array

The following array:
Copy codeThe Code is as follows:
Var persons = [["zhangsan", 25], ["lisi", 21], ["wangwu", 32];

By multiplying the dimension (3) by the number of elements in each dimension (2), we can see that the number of elements in the multi-dimensional array is 6. But this is not an insurance practice, because the number of elements in each dimension in a multi-dimensional array can be different, such:

Copy codeThe Code is as follows:
Var persons = [["zhangsan", 25], ["lisi", 21,172], ["wangwu", 32];

The second element array of the first dimension of the array contains three elements, and the other has only two elements. In this case, length is used to calculate 3, because the number of elements in the first dimension has not changed. However, using the above method to calculate the number of elements in the multi-dimensional array is incorrect.
Therefore, the length attribute of a multi-dimensional array is the same as that of a one-dimensional array, and the number of elements in the First-dimensional array is always returned. To calculate the number of elements in a multi-dimensional array, you can create one or more nested for loops for calculation. for example:
When you know the dimension of an array, you can write an algorithm for this array, such as a two-dimensional array:

var persons = [["zhangsan", 25], ["lisi", 21], ["wangwu", 32]];function getArr2ElementNum(arr) {var eleNum = 0;if (arr == null) {return 0;}for (var i = 0; i < arr.length; i++) {for (var j = 0; j < arr[i].length; j++) {eleNum++;}}return eleNum;}alert(getArr2ElementNum(persons));


When there are too many dimensions in a multi-dimensional array and the nesting is complex, it is too tired to write targeted algorithms through the above method, especially when the complex multi-dimensional array may change the dimension at any time. The complex multi-dimensional array with multiple nesting parameters is as follows:
Var arrN = [["zhangsan", 25, [1, "wangyuchu", 54, [123, 34, 16], 43], ["lisi", 21,172], ["wangwu", 32, "suzhou"];
Even some multi-dimensional nested arrays are more complicated than this. How can we calculate the number of array elements? I wrote a function to calculate the number of array elements, whether it is one-dimensional or multi-dimensional, no matter how complicated a nested multi-dimensional array can be computed, the algorithm is not troublesome and mainly uses the concept of recursion:
// Determine whether an object is an array

Function isArray (obj) {return obj & (typeof obj = 'object') & (obj. constructor = Array);} // the initial value of the eleNum variable is 0, which is used to calculate the number of Array elements var eleNum = 0; // recursively calculates whether an Array element is a next-dimensional Array. If yes, recursion continues. If not, the number of elements is counted. Function recursion (obj) {if (isArray (obj) {for (var j = 0; j <obj. length; j ++) {if (! IsArray (obj [j]) {eleNum ++; continue;} recursion (obj [j]) ;}} else {eleNum ++ ;}} // arr is a one-dimensional or multi-dimensional array to calculate the number of array elements. by calling the recursive function recursion, return the number of array elements. function getArrNElementNum (arr) {if (arr = null) {return 0;} recursion (arr); return eleNum;} // define a complex multi-dimensional nested array var arrN = [["zhangsan", 25, [1, "wangyuchu", 54, [123, 34, 16], 43], ["lisi", 21,172], ["wangwu", 32, "suzhou"]; // print out the number of array elements alert (getArrNElementNum (arrN ));

Object:
Objects are separated by curly brackets. Within the brackets, the attributes of an object are defined in the form of name and value pairs (name: value. Attributes are separated by commas:
Copy codeThe Code is as follows:
Var person = {firstname: "Bill", lastname: "Gates", id: 5566 };

The object (person) in the preceding example has three attributes: firstname, lastname, and id.
Spaces and lines do not matter. The statement can span multiple rows:

var person={firstname : "Bill",lastname : "Gates",id    : 5566};

There are two addressing methods for object attributes:
Instance

name=person.lastname;name=person["lastname"];

Mixed use of objects and multi-dimensional arrays:
Imagine a scenario where we want to enumerate and count the total number of departments of Tsinghua University (qinghua), Peking University (beida), and Zhejiang University (zheda). How can we do this?
First, create an array containing three schools:
Copy codeThe Code is as follows:
Var parameters = [qinghua, beida, zheda];

Each school has many different or identical colleges (xx? Here we need to use an array containing objects:
Copy codeThe Code is as follows:
Var scripts = [qinghua {xx1, xx2, xx3}, beida {xx4, xx5,
Xx6, xx7}, zheda {xx8, xx9}];

Each school has a different department (d?
Copy codeThe Code is as follows:
Var parameters = [qinghua {xx1: [d1, d2], xx2 [d3, d5],
Xx3: [d7, d8]}, beida {xx4, xx5, xx6, xx7}, zheda {xx8,
Xx9}];
// For example, I will not represent the next two universities.

The preceding example is an array. The element of this array is a school object. The school object has N school attributes, and each school attribute is an array containing multiple departments, this is a typical example of mixed use of multi-dimensional arrays and objects. It can be a simple and clear description of the level, ownership, and Quantity Relationship between schools, schools, and departments.

Articles you may be interested in:
  • How to implement multi-dimensional array using JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.