17.数组
1.数组
1.1创建数组
const arr1 = new Array(); //方法一
const arr2 = []; //方法二
1.2数组内添加元素
//方法一
const arr2 = [1, 2, 3, 4, 5];
//方法二
arr1[0] = 11
arr1[1] = 22
使用数组时,应避免非连续数组,性能不好
arr1[9] = 99
console.log("arr1 = " + arr1); //arr1 = 11,22,,,,,,,,99
console.log("arr2 = " + arr2); //arr2 = 1,2,3,4,5
1.3读取数组元素
console.log(arr1[0]); //11
console.log(arr2[0]);//1
1.4数组长度
//自定义数组长度
arr1.length = 100
arr2.length = 10
//获取数组长度
console.log(arr1.length); //10
console.log(arr2.length); //5
//数组的数据类型
console.log(typeof arr1); // object
//数组末尾添加元素
arr1[arr1.length] = 123
console.log(arr1[100]);
1.5数组的遍历
const arr = ["孙悟空", "猪八戒", "沙和尚"]
for (i of arr) {
console.log(i);
//孙悟空
//猪八戒
//沙和尚
}