Home >Web Front-end >JS Tutorial >Mixed use of js one-dimensional arrays, multi-dimensional arrays and objects_javascript skills

Mixed use of js one-dimensional arrays, multi-dimensional arrays and objects_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:06:521576browse

The main purpose of this article is to explain the mixed use of JavaScript arrays and objects. Due to the weak checking characteristics of JS, different types of variables can be stored in JS arrays at the same time. For example, you can store numbers, strings, characters, Objects and other contents are placed in the same array. Objects can also do the same thing. The difference is that objects can specify aliases for each member in the object, so that the data is more readable during programming, such as:

var arr1 = ["飞鱼", 25, 172, "江苏"];
var person = {name:"飞鱼",age: 25, height:172,province: "江苏"};

In this way, is person.name easier to read and use than arr1[0]? Of course, arrays and objects each have their own advantages. The focus of this article is to combine the advantages of both and use them comprehensively.

One-dimensional array
The following code creates an array named cars: first create the array, and then assign values ​​one by one

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

or (condensed array): assign value when creating array object

Copy code The code is as follows:

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

Or (literal array): Do not create variables, directly assist, but pay attention to the parentheses "( )" used when creating objects, and the square brackets "[ ]" used when assigning values ​​directly. This can easily lead to errors if you are not careful.
Example
Copy code The code is as follows:

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

The above are three ways to create a one-dimensional array. Due to the weak checking nature of JS, you can put variables of different types in a one-dimensional array.

Two-dimensional and multi-dimensional arrays:
1. Method 1 of creating a two-dimensional array: First create a one-dimensional array, and then create one-dimensional data for all members of the one-dimensional array

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 one is much simpler and easier to read.

Copy code The code is as follows:

persons.length = 3

​ ​ 2. Method 2 of creating a two-dimensional array: First create a one-dimensional array, and then directly assign values ​​to all members of the one-dimensional array
Copy code The code is as follows:

var persons = new Array();

3. Method 3 of creating a two-dimensional array: direct assignment
Copy code The code is as follows:

var persons = [["zhangsan", 25], ["lisi", 21], ["wangwu", 32]];

4. Summary
Although the first and second methods are more troublesome, you can first create an empty multi-dimensional array and then assign values ​​according to your own needs in the for loop. The third method is relatively simple and easy to use for enumerated data.
The last question about two-dimensional arrays is what is the length of a two-dimensional or multi-dimensional array? Let’s test the following code:

Copy code The code is as follows:

document.write("persons = " + persons + "df250b2156c434f3390392d09b1c9563persons.length = " + persons.length);

The output result is:
           persons = zhangsan,25,lisi,21,wangwu,32
In other words, the length property of a multi-dimensional array returns the length of the first dimension of the multi-dimensional array, not the number of elements in the multi-dimensional array.

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

The following array:

Copy code The code is as follows:

var persons = [["zhangsan", 25], ["lisi", 21], ["wangwu", 32]];

通过维数(此处是3)乘以每维元素的个数(此处是2)就可以得出该多维数组的元素个数是6了。但是这并不是保险的做法,因为多维数组中每一个维度的元素个数是可以不一样的,如:

复制代码 代码如下:

var persons = [["zhangsan", 25], ["lisi", 21, 172], ["wangwu", 32]];

        该数组的第一维的第二个元素数组包含三个元素,其他的只有两个,这再使用length来计算还是3,因为第一维的元素个数没变嘛。但是再使用上面的方法计算该多维数组的元素个数就不对了。
        因此多维数组的length属性和一维数组一样,永远返回第一维数组的元素个数。计算多维数组的元素个数,可以自己创建一个或多个嵌套for循环来计算,如:
        在知道数组的维度的情况下,可以针对该数组写算法,如二维数组:

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));


      在多维数组维度过多,嵌套复杂时,通过上面的方法来写针对的算法就太累了,特别是当这个复杂的多维数组还可能随时变换维度的情况下。如下这个复杂的多重嵌套的多维数组:
var arrN = [["zhangsan", 25, [1, "wangyuchu", 54, [123, 34, 16]], 43], ["lisi", 21, 172], ["wangwu", 32, "suzhou"]];
      甚至,有些多维嵌套数组比这个还复杂,那怎么计算数组元素个数呢,我写了一个求数组元素个数的函数,不管是一维还多维,也不管是多么复杂的嵌套多维数组,都可以计算出来,算法不麻烦,主要用到了递归的理念:
//判断某个对象是不是数组

function isArray(obj) {
return obj && ( typeof obj === 'object') && (obj.constructor == Array);
}

//eleNum变量初始值为0,用来统计数组元素个数
var eleNum = 0;

//递归计算某个数组元素是不是下一维数组,如果是,则继续递归下去;如果不是,统计元素个数。
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为要计算数组元素个数的一维或多维数组,通过调用递归函数recursion返回数组元素个数
function getArrNElementNum(arr) {
if (arr == null) {
return 0;
}

recursion(arr);

return eleNum;
}

//随意定义一个复杂的多维嵌套数组
var arrN = [["zhangsan", 25, [1, "wangyuchu", 54, [123, 34, 16]], 43], ["lisi", 21, 172], ["wangwu", 32, "suzhou"]];
//打印出来数组元素个数
alert(getArrNElementNum(arrN));

对象:
对象由花括号分隔。在括号内部,对象的属性以名称和值对的形式 (name : value) 来定义。属性由逗号分隔:

复制代码 代码如下:

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

上面例子中的对象 (person) 有三个属性:firstname、lastname 以及 id。
空格和折行无关紧要。声明可横跨多行:
var person={
firstname : "Bill",
lastname : "Gates",
id    : 5566
};

对象属性有两种寻址方式:
实例

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

对象和多维数组的混合使用:
         想象这么一个场景,要枚举并统计清华大学(qinghua)、北京大学(beida)、浙江大学(zheda)三所大学一共有多少个系,怎么做?
         首先,建立一个数组,数组中包括着三所学校:

复制代码 代码如下:

var departments = [qinghua, beida, zheda];

        每个学校又有很多不同或相同的学院(xx),如何表示?在这里就要用到数组包含对象了:
复制代码 代码如下:

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

每个学院又有不同的系(d),如何表示?
复制代码 代码如下:

var departments = [qinghua{xx1:[d1, d2], xx2[d3, d5],
 xx3:[d7, d8]}, beida{xx4, xx5, xx6, xx7}, zheda{xx8,
 xx9}];
 //只是举个例子,后面两个大学我就不表示了

上述例子就是一个数组,该数组的元素是学校对象,学校对象有N个学院属性,而每个学院属性又是一个包含多个系的数组,这就是一个典型的多维数组和对象混合使用的例子,可以简单明了的说明和列表学校、学院和系之间的级别、归属和数量关系。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn