JavaScript--数组的声明与创建

我们知道Object是使用new关键字或者字面量表示法进行声明与创建的。

那么应用类型--Array也可以用类似的方法进行声明与创建。

一、new关键字创建数组:new Array();

var colors = new Array();
console.log(colors);
console.log(colors.length);
colors[0] = '1';
colors[1] = 2;
console.log(colors);

二、显示声明数组的长度,如new Array(10);

var colors2 = new Array(20);
console.log(colors2);
console.log(colors2.length);
colors2[20] = '2';
console.log(colors2); //前20个为空 第二十一项为2
console.log(colors2[20]); //第二十一项 2
console.log(colors2.length); //总长度为21

三、在Array()方法中直接加入初始值,如new Array(1,2,3);

var colors3 = new Array(1, '2', 3.0);
console.log(colors3);
console.log(colors3.length);
colors3[3] = colors2;
console.log(colors3);
console.log(colors3.length);

注意:二和三的表示形式需要区分开,当我们使用Array()的括号中只有一个数字时,则表示的是方法二,数字表示数组长度;当new Array()中放入的是'3'字符串,则表示的方法三,数组初始长度为1。

var cc = new Array(3); //声明了一个初始长度为3的数组
var dd = new Array('3'); //声明了一个长度为一 且第一位的值为3的数组
console.log(cc);
console.log(dd);

四、在证明Array时 还可以省略new关键字,Array()、Array(3)、Array('3')都是合法的

五、Array也有字面量表示法

var colors4 = ['red', 2, 4.0]; //创建一个长度为3的数组
console.log(colors4);
var colors5 = []; //长度为0的数组
colors5[0] = '1'; //新增一项
colors5[0] = 3; //修改第一项
console.log(colors5); //[3]
console.log(colors5.length);

猜你喜欢

转载自www.cnblogs.com/bigbosscyb/p/12168679.html