A hybrid method for JS one-dimensional arrays, multidimensional arrays and objects _javascript tips

Source: Internet
Author: User
Tags mixed

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"};

So is person.name 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

Copy Code code as follows:

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
Copy Code code as follows:

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] =;
Persons[1][0] = "Lisi";
PERSONS[1][1] =;
Persons[2][0] = "Wangwu";
PERSONS[2][1] =;
Persons[0] = ["Zhangsan",];
PERSONS[1] = ["Lisi",];
PERSONS[2] = ["Wangwu", 32];

This is easier to read than the previous method.

Copy Code code as follows:

Persons.length = 3

2. Create a two-dimensional array method two: first create a one-dimensional array, and then all members of the one-dimensional array are assigned directly
Copy Code code as follows:

var persons = new Array ();

3. Create two-dimensional array method three: Direct assignment
Copy Code code as follows:

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 question in a two-dimensional array is what is the length of a two-dimensional array or a multidimensional array? Let's test the following code:

Copy Code code as follows:

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:

Copy Code code 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:

Copy Code code as follows:

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",]];
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 that is used in the above method, especially if the complex multidimensional array may change the dimension at any time. This complex multidimensional array of multiple nesting:
var arrn = [[Zhangsan], [1, "Wangyuchu", Si, [123, M,]], [Lisi], 172], ["Wangwu", , "Suzhou"]];
      Even, some multidimensional arrays are more complex than this, how to calculate the number of array elements, I wrote a function to find the number of elements of the array, whether one-dimensional and multidimensional, no matter how complex a nested multidimensional array, Can be calculated, the algorithm is not troublesome, the main use of the concept of recursion:
//To determine whether an object is not 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 count the number of 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 of an array, recursion returns the number of array elements by calling a recursive 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,,,]], [Lisi], 172], ["Wangwu" , "Suzhou"];
Print out the number of array elements
alert (Getarrnelementnum (ARRN));

Object:
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:

Copy Code code as follows:

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 such a scene, to enumerate and statistic how many departments are there in the three universities (Qinghua), Peking University (Beida) and Zhejiang College (Zheda)?
First, create an array that includes three schools:

Copy Code code as follows:

var departments = [Qinghua, Beida, Zheda];

Each school also has many different or the same school (XX), how to express? The array contains objects are used here:
Copy Code code as follows:

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

Each college has a different system (d), how to express it?
Copy Code code as follows:

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.