JavaScript - 数组
数组的组成:
- 数组元素 – 组成数组的每一个数据;
- 数组索引 – 每一个元素对应的下标;
- 数组访问 – 数组名[索引];
- 数组长度 – 数组元素的个数;
数组的定义:
方式一:实例化
let arr = new Array(1,2,3);
console.log(arr);
方式二:字面量
let arr = [1,2,3,4];
操作方法(访问数组中的元素):
1.访问数组长度:arr.length;
2.访问数组的元素:arr[索引];
语法:数组变量名[索引值]
例如:arr2[1]
console.log(arr2[1]);
3.增加数组的元素:arr[新的索引] arr[arr.length]
let names=['小乔', '大乔'];
names[2]='貂蝉'; //给不存在的下标添加元素
names[names.length]='杨玉环'; //取数组长度作为下标
4.修改数组的元素:arr[索引] = "新的值";
let names=['小乔', '大乔'];
names[0]='貂蝉'; //给存在的下标设置元素
5.删除数组的元素:delete arr[索引] -- 不用
数组的遍历:(精通)
for循环遍历:
for(let i = 0;i < arr.length;i++){
i -- 数组元素的索引
arr[i] -- 数组的元素
let arrNum=arr[i]; //所有数组元素
console.log(i); //索引
console.log(arrNum);
}
forEach()遍历:
arr.forEach(function(v,i){
v -- 数组的元素
i -- 元素的索引
console.log(index); //索引
console.log(value); //数组元素
})
数组的常用方法:
join() -- 把数组以指定的符号转为字符串,不写,默认为逗号(,)
let arr = [1, 2, 3];
let str = arr.join('-'); //设置分隔符
console.log( str ); //1-2-3
pop() -- 删除数组的最后一个元素
let arr = [1, 2, 3];
let v = arr.pop(); //删除最后一个元素,并返回
console.log( v, arr ); //3 [1, 2]
push() -- 往数组的最后添加元素
let arr = [1, 2, 3];
let v = arr.push(4, 5, 6); //添加元素到最后,返回长度
console.log( v, arr ); //6 [1, 2, 3, 4, 5]
splice(2,1,'hh') -- 参数1:索引 参数2:删除的个数 参数3:你要做的操作;
let arr = [1, 2, 3];
let v = arr.push(4, 5, 6); //添加元素到最后,返回长度
console.log( v, arr ); //6 [1, 2, 3, 4, 5]
includes() -- 检测数组中是否包含某个元素,包含,返回true,反之
let arr = [1, 2, 3];
let v = arr.push(4, 5, 6); //添加元素到最后,返回长度
console.log( v, arr ); //6 [1, 2, 3, 4, 5]