1. 使用Array构造函数创建
![数组的创建方式-Array构造函数.png](https://i-blog.csdnimg.cn/blog_migrate/e6dc428b45d144eddce19b7522cd29f2.webp?x-image-process=image/format,png)
数组的创建方式-Array构造函数.png
a、var arr1 = new Array(); //创建空数组
b、var arr2 = new Array(10); //创建一个长度为10的数组
c、var arr3 = new Array(5,4,3,2,1); //创建数组并初始化
2. 采用数组字面量方式创建
var arr = []; //创建一个空数组
var arr2 = [1,2,3]; //创建一个有三个元素的数组
练习1:定义一个空数组,往数组中存入个人信息,并输出
第一种方式:
var person = ["小明", 20, 180];
console.log(person);
输出:
![创建空数组.png](https://i-blog.csdnimg.cn/blog_migrate/411505a6ceff8f99f7edaa44f20f7081.webp?x-image-process=image/format,png)
创建空数组.png
第二种方式:
var person = [];
person[0] = "小明";
person[1] = 20;
person[2] = 180;
console.log(person);
输出:
![创建空数组.png](https://i-blog.csdnimg.cn/blog_migrate/9ef07be16511c17dcc2b008ea1fe629e.webp?x-image-process=image/format,png)
创建空数组.png
练习2:遍历数组[10, 1, 19, 22, 73, 88, 99],将其中的偶数输出
var numbers = [10, 1, 19, 22, 73, 88, 99];
for (i = 0; i < numbers.length; i++) {
var item = numbers[i];
if (item % 2 === 0){ //偶数
console.log(item);
}
}
输出:
![练习2.png](https://i-blog.csdnimg.cn/blog_migrate/925299bed922c78cce1088a91abf9afb.webp?x-image-process=image/format,png)
练习2.png
练习3:求一组数中的最大值和最小值,以及所在的位置
var numArr = [1, 99, 88, -100, 77, 888, 1000, -1000];
var maxValue = numArr[0], minValue = numArr[0]; //最大值 和 最小值
var maxIndex = 0, minIndex = 0; //最大值索引 和 最小值索引
for (i = 0; i < numArr.length; i++) {
//如果数组中的元素大于我们定义的初始值
if (maxValue < numArr[i]) {
//把这个元素赋值给最大值,并把索引改变
maxValue = numArr[i];
maxIndex = i;
}
if (minValue > numArr[i]) {
minValue = numArr[i];
minIndex = i;
}
}
console.log(maxValue);
console.log(maxIndex);
console.log(minValue);
console.log(minIndex);
输出:
![练习3](https://i-blog.csdnimg.cn/blog_migrate/72c0b7d9444011d4add942f358ab680d.webp?x-image-process=image/format,png)
练习3
练习4:将数组中值为0的去掉,不为0的存入一个新数组
var arr = ["张三", 18, 0, "男", 0, 12243, 0]
var newArr = [];
for (i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
newArr[newArr.length] = arr[i];
}
}
console.log(newArr);
输出:
![练习4.png](https://i-blog.csdnimg.cn/blog_migrate/3e4e5e0cc022668be690a0516a5d8bb0.webp?x-image-process=image/format,png)
练习4.png