3 ways to create an array in javaScript

JS array definition and detailed explanation

How does javascript define an array?

Directly upload code and screenshots

//javaScript中创建数组的3种方式
//方式1
var names = ["令狐冲", "张无忌", "韦小宝", "杨过"];
for (var index = 0; index < names.length; index++) {
	console.log(names[index]);
}
//方式2
var citys = new Array("于都县", "兴国县", "会昌县", "赣县");
for (var index = 0; index < citys.length; index++) {
	console.log(citys[index]);
}
//方式3
var superStars = new Array(3);//固定数组长度为3
superStars[0] = "黄晓明";
superStars[1] = "周杰伦";
superStars[2] = "Angelababy";
for (var index = 0; index < superStars.length; index++) {
	console.log(superStars[index]);
}
//
var hobbys = new Array(4);
//如下:不按顺序赋值也是可以的
hobbys[1] = "看书";
hobbys[3] = "下棋";
hobbys[0] = "爬山";
hobbys[2] = "足球";
for (var index = 0; index < hobbys.length; index++) {
//可以正常循环打印出来,并不会报错	
	console.log(hobbys[index]);
}
//数组中如果不添加元素,那打印出来的元素的值默认就是undefined
var score = new Array(3);
for (var index = 0; index < score.length; index++) {
	console.log("第" + (index+1) + "个元素的值是" + score[index]);
}

The results of the operation are as follows:

Add more

//不定义元素个数
var superStars = new Array();
superStars[0] = "杨幂";
superStars[1] = "易烊千玺";
superStars[2] = "迪丽热巴";
superStars[3] = "鹿晗";
superStars[4] = "黄子韬";
for (var index = 0; index < superStars.length; index++) {
	console.log(superStars[index]);
}

The results of the operation are as follows:

Guess you like

Origin blog.csdn.net/czh500/article/details/114490260