# JS一维数组、多维数组和对象的混合使用

var arr1 = ["飞鱼", 25, 172, "江苏"];

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

var cars=new Array();

cars[0]="Audi";

cars[1]="BMW";

cars[2]="Volvo";

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

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

1、创建二维数组方法一：先创建一个一维数组，然后该一维数组的所有成员再创建一维数据

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

persons.length = 3

2、创建二维数组方法二：先创建一个一维数组，然后该一维数组的所有成员直接赋值

var persons = new Array();

3、创建二维数组方法三：直接赋值

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

4、总结

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

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

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

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

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

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;

}

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

//打印出来数组元素个数

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

var person={

firstname : "Bill",

lastname  : "Gates",

id        :  5566

};

name=person.lastname;

name=person["lastname"];

var departments = [qinghua, beida, zheda];

var departments = [qinghua{xx1, xx2, xx3}, beida{xx4, xx5,

xx6, xx7}, zheda{xx8, xx9}];

var departments = [qinghua{xx1:[d1, d2], xx2[d3, d5],

xx3:[d7, d8]}, beida{xx4, xx5, xx6, xx7}, zheda{xx8,

xx9}];

//只是举个例子，后面两个大学我就不表示了