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

 

introduction

       The main purpose of this article is to explain the mixed use of JavaScript arrays and objects. Due to the weak checking feature 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, etc. in the same array. Objects can also do the same thing, the difference is that the object can specify the alias of each member in the object, which makes the data 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, is person.name more readable and easier to use than arr1[0]? Of course, arrays and objects have their own advantages. The focus of this article is to combine the advantages of the two and use them comprehensively.

 

one-dimensional array

 

The following code creates an array named cars: first create the array, then assign each value

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

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

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

Or (literal array): Do not create variables, directly assist, but pay attention to the parentheses "( )" when creating objects, and the square brackets "[ ]" when assigning directly, which is prone to errors if you are not careful.

example

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

 

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

 

Two-dimensional and multidimensional arrays:

      1.  Create a two-dimensional array method 1: 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 to the previous method, this one is much simpler and easier to read.
      

persons.length = 3

 

       2. Method 2 of creating a two-dimensional array: first create a one-dimensional array, and then assign all members of the one-dimensional array directly

var persons = new Array();

       3. Method 3 of creating a two-dimensional array: direct assignment

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

       4. Summary

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

       二维数组的最后一个问题,就是二维数组或多维数组的长度是多少?我们测试一下下面的代码:

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

       输出的结果是:

            persons = zhangsan,25,lisi,21,wangwu,32

    也就是说,多维数组的length属性返回的是多维数组第一维的长度,而不是多维数组中元素的个数。

   5、如何返回多维数组的元素个数

如下数组:

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[d 3 , d 5 ], xx3 :[d7, d8] }, beida{xx4, xx5, xx6, xx7}, zheda{xx8, xx9}] ;

//Just to give an example, I will not express the latter two universities

 

        The above example is an array. The elements of the array are school objects. The school object has N college attributes, and each college attribute is an array containing multiple departments. This is a typical example of mixed use of multidimensional arrays and objects. , which can explain and list the level, affiliation and quantitative relationship between schools, colleges and departments in a simple and clear way.

 

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

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326495138&siteId=291194637