1. 创建数组
1.1 使用new Array()
let arr = new Array();
console.log(typeof arr);
结果:
object
1.2 使用中括号
let arr = [];
console.log(typeof arr);
结果:
object
2. 访问数组
let arr = [1,2,3,4,5];
let a = arr[0];
let b = arr[arr.length-1];
console.log(a,b);
结果:
1 5
3. 增加数组元素
3.1 初级方法
let arr = [];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
console.log(arr);
结果:
[1, 2, 3, 4]
3.2 使用push方法,在数组末尾添加元素
let arr = [];
arr.push(11);
arr.push(22);
arr.push(33);
arr.push(44);
arr.push(55);
console.log(arr);
结果:
[11, 22, 33, 44, 55]
3.3 使用unshift方法,在数组头部添加元素
let arr = [];
arr.unshift(11);
arr.unshift(22);
arr.unshift(33);
arr.unshift(44);
arr.unshift(55);
console.log(arr);
结果:
[55, 44, 33, 22, 11]
4. 修改数组元素
let arr = [];
arr.unshift(11);
arr.unshift(22);
arr.unshift(33);
arr.unshift(44);
arr.unshift(55);
console.log(arr);
arr[2] = 66;
arr[3] = 77;
console.log(arr);
结果:
[55, 44, 33, 22, 11]
[55, 44, 66, 77, 11]
5. 删除数组元素
5.1 删除数组末尾的元素,pop方法
let arr = [];
arr.unshift(11);
arr.unshift(22);
arr.unshift(33);
arr.unshift(44);
arr.unshift(55);
arr.unshift(66);
arr.unshift(77);
console.log(arr);
arr.pop();
console.log(arr);
arr.pop();
console.log(arr);
结果:
[77, 66, 55, 44, 33, 22, 11]
[77, 66, 55, 44, 33, 22]
[77, 66, 55, 44, 33]
5.2 删除数组开头的元素,shift方法
let arr = [];
arr.unshift(11);
arr.unshift(22);
arr.unshift(33);
arr.unshift(44);
arr.unshift(55);
arr.unshift(66);
arr.unshift(77);
console.log(arr);
arr.shift();
console.log(arr);
arr.shift();
console.log(arr);
结果:
[77, 66, 55, 44, 33, 22, 11]
[66, 55, 44, 33, 22, 11]
[55, 44, 33, 22, 11]
5.3 通过索引值删除一个元素
let arr = [];
arr.unshift(11);
arr.unshift(22);
arr.unshift(33);
arr.unshift(44);
arr.unshift(55);
arr.unshift(66);
arr.unshift(77);
console.log(arr);
let delItem = arr.splice(1,1);
console.log(delItem);
console.log(arr);
结果:
[77, 66, 55, 44, 33, 22, 11]
[66]
[77, 55, 44, 33, 22, 11]
5.4 通过索引值删除多个元素
let arr = [];
arr.unshift(11);
arr.unshift(22);
arr.unshift(33);
arr.unshift(44);
arr.unshift(55);
arr.unshift(66);
arr.unshift(77);
console.log(arr);
let delItem = arr.splice(1,3);
console.log(delItem);
console.log(arr);
结果:
[77, 66, 55, 44, 33, 22, 11]
[66, 55, 44]
[77, 33, 22, 11]
6. 查询数组
let arr = [];
arr.unshift(11);
arr.unshift(22);
arr.unshift(33);
arr.unshift(44);
arr.unshift(55);
arr.unshift(66);
arr.unshift(77);
console.log(arr);
arr.forEach(function(item,index,arrs){
console.log(item,index);
})
结果:
[77, 66, 55, 44, 33, 22, 11]
77 0
66 1
55 2
44 3
33 4
22 5
11 6
7. 查找数组元素的索引
let arr = [];
arr.unshift(11);
arr.unshift(22);
arr.unshift(33);
arr.unshift(44);
arr.unshift(55);
arr.unshift(66);
arr.unshift(77);
console.log(arr);
let a = arr.indexOf(44);
console.log(a);
let b = arr.lastIndexOf(33);
console.log(b);
结果:
[77, 66, 55, 44, 33, 22, 11]
3
4
8. 复制数组
let arr = [];
arr.unshift(11);
arr.unshift(22);
arr.unshift(33);
arr.unshift(44);
arr.unshift(55);
arr.unshift(66);
arr.unshift(77);
console.log(arr);
let carr = arr.slice();
console.log(carr);
结果:
[77, 66, 55, 44, 33, 22, 11]
[77, 66, 55, 44, 33, 22, 11]