Mixed use of JS one-dimensional arrays, multidimensional arrays, and objects

Source: Internet
Author: User

Reprint Address: http://blog.csdn.net/wangyuchun_799/article/details/38460515

Introduction

The main purpose of this article is to explain the mixed use of JavaScript arrays and objects, because of the weak check characteristics of JS, so in the JS array can store different types of variables, such as you can put numbers, strings, characters, objects and other content in the same array. objects can do the same thing, except that an object can specify an alias for each member of the object, so that the data is easier to read when programming, such as:

var arr1 = ["Flying Fish", 25, 172, "Jiangsu"];

var person = {name: "Flying Fish", age:25, Height:172,province: "Jiangsu"};

In this way, person.name is easier to read than arr1[0] and easier to use. Of course, the array and objects have advantages, the focus of this paper is to combine the advantages of the two, integrated use.


one-dimensional arrays

The following code creates an array named cars: first create an array, then one by one assignment

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

or (condensed array): Assigning values when an array object is created

var cars=new Array ("Audi", "BMW", "Volvo");

or (literal array): Do not create a variable, directly auxiliary, but note that the creation of the object with the parentheses "()", and the direct assignment with the square brackets "[]", this inadvertently error prone. Instance

var cars=["Audi", "BMW", "Volvo"];

Above are three ways to create a one-dimensional array. because of the weak check of JS, you can put different types of variables in a one-dimensional array.


Two-dimensional and multidimensional arrays: 1, Create a two-dimensional array method one: first create a one-dimensional array, and then all members of the one-dimensional array to 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];

This is easier to read than the previous method.

Persons.length = 3 2, creating a two-dimensional array method two: first create a one-dimensional array, and then all members of the one-dimensional array are assigned directly

var persons = new Array (); 3. Create two-dimensional array method Three: Direct Assignment

var persons = [["Zhangsan",], ["Lisi",], ["Wangwu", 32]]; 4, Summary

The first and second methods are troublesome, but expensive you can create an empty multidimensional array first, and then assign values to your needs in the For loop. The third method is easier to use for enumerating data.

The last problem with a two-dimensional array is how long a two-dimensional array or multidimensional array is. Let's test the following code:

document.write ("persons =" + Persons + "<br/>persons.length =" + persons.length);

The result of the output is:

Persons = Zhangsan,25,lisi,21,wangwu,32

That is, the length property of the multidimensional array returns the first dimension of the multidimensional array, not the number of elements in the multidimensional array. 5, how to return the number of elements of a multidimensional array

Array as follows:

var persons = [["Zhangsan",], ["Lisi",], ["Wangwu", 32]];

The number of elements in the multidimensional array is 6 by multiplying the number of dimensions (here, 3) by the number of elements per dimension (here is 2). This is not an insurance practice, however, because the number of elements for each dimension in a multidimensional array can be different, such as:

var persons = [["Zhangsan",], ["Lisi", 172], ["Wangwu", 32]];

The second element of the first dimension of the array contains three elements, the other only two, which uses length to calculate or 3, because the number of elements in the first dimension does not change. However, it is wrong to use the above method to calculate the number of elements in the multidimensional array.

Therefore, the length property of a multidimensional array, like a one-dimensional array, returns the number of elements of the first-dimensional array forever. To calculate the number of elements in a multidimensional array, you can create one or more nested for loops to calculate, such as:

When you know the dimensions of an array, you can write an algorithm for that array, such as a two-dimensional array:

var persons = [["Zhangsan",], ["Lisi",], ["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 multidimensional array dimensions are too large and nesting is complex, it is tiring to write the algorithm in the above way, especially when the complex multidimensional array may change the dimension at any time. This complex, multiple nested multidimensional array is as follows:

var arrn = [["Zhangsan", [1, "Wangyuchu", Si, [123, N,]], ["Lisi", 172], ["Wangwu", "Suzhou"]];

Even some multidimensional arrays are more complex than this, then how to calculate the number of elements of the array, I wrote an array of elements to find the number of functions, whether it is one-dimensional and multidimensional, and no matter how complex the nested multidimensional array, can be calculated, the algorithm is not troublesome, mainly used the concept of recursion:

To determine if an object is not an array

function IsArray (obj) {

return obj && (typeof obj = = ' object ') && (obj.constructor = = Array);

}


The Elenum variable has an initial value of 0, which is used to count the array elements

var elenum = 0;


Recursively computes whether an array element is the next one-dimensional array, and if so, continues recursively; if not, count the number of elements.

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 multidimensional array to compute the number of elements in an array, recursion returns the number of array elements by calling a recursive function

function Getarrnelementnum (arr) {

if (arr = = null) {

return 0;

}


Recursion (arr);


return elenum;

}


Arbitrarily define a complex multidimensional nested array

var arrn = [["Zhangsan", [1, "Wangyuchu", Si, [123, N,]], ["Lisi", 172], ["Wangwu", "Suzhou"]];

Print out the number of array elements

Alert (Getarrnelementnum (ARRN)); objects:

Objects are delimited by curly braces. Within parentheses, the object's properties are defined in the form of name and value pairs (name:value). Properties are separated by commas:

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

The object (person) in the example above has three properties: FirstName, LastName, and ID.

Spaces and folding lines are irrelevant. Declarations can span multiple lines:

var person={
FirstName: "Bill",
LastName  : "Gates",
ID        :  5566
};

There are two ways to address object properties:

Instance

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

mixed use of objects and multidimensional arrays:

Imagine a scene that enumerates and counts how many departments there are in three universities in Tsinghua University (Qinghua), Beijing University (Beida) and Zhejiang College (Zheda).

First, create an array that includes three schools:

var departments = [Qinghua, Beida, Zheda];

Each school has many different or identical colleges (XX), how to express. The array contains objects are used here:

var departments = [Qinghua:{xx1, xx2, xx3}, beida:{xx4, xx5, xx6, xx7}, zheda:{xx8, xx9}];

Each college has a different system (d) and how it is expressed.

var departments = [Qinghua:{xx1:[d1, D2], Xx2:[d3, D5], Xx3:[d7, D8]}, beida:{xx4, xx5, xx6, xx7}, zheda:{xx8, xx9}];

Just for example, I don't show up at the back two universities.

The example above is an array of elements that are school objects, the school object has n college attributes, and each college attribute is an array of multiple systems, which is a typical example of multidimensional array and object blending, which can be used to describe and list the level, attribution, and quantity relationships between schools, colleges, and departments in a straightforward way.

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.