1、创建数组
var arr = new Array(); // [ ]
var arr = new Array(5); // [ , , , , ]
var arr = new Array(1,2,3,4,5); [1,2,3,4,5];
var arr = [ ];
var arr = [1,2,3,4,5];
ES6中新增:
var arr = Array.of(5) // [5]
初始化数组:
var arr = new Array(5); // [ , , , , ]
arr.fill(0) // [0, 0, 0, 0, 0]
2、获取
1)通过[ ] 或 点.
2)获取数组最后一个元素: arr[arr.length-1]
3)获取某个范围内元素:splice
var arr2 = [1,2,3,4,6]; var result = arr2.slice(1,3) console.log(result) // [2, 3]
3、增
1)push , unshift
2)splice
var arr3 = [1,2,3,4,6]; var result = arr3.splice(2,0,"sdf") //第二个位置,删除0个元素,插入值 console.log(arr3) // [1, 2, "sdf", 3, 4, 6]
3)设置数组长度 length
var arr = [1,2]; arr[arr.length] = 3 console.log(arr); // [1, 2, 3]
arr.length = 100 ;
console.log(arr.length) // 100 只是后面的元素值为undefined
4、删
1)删除一个:pop, shift
2)splice
var arr2 = [1,2,3,4,6]; var result = arr2.splice(1,3) console.log(result) // [2, 3, 4] 删除的值 console.log(arr2) // [1, 6] 删除后得到的值
3)delete
var arr = [1, 2, 3, 4]; delete arr[0]; console.log(arr); //[undefined, 2, 3, 4] delete删除之后数组长度不变,只是被删除元素被置为undefined了
4)数组属性length
var t = [1,23,5,6,7]; t.length =3; console.log(t) // [1,23,5]
5)清空数组
a、arr.length = 0
b、arr = [ ]
区别: var arr = [1,23,5,6,7]; var arr1 = arr; arr.length = 0; console.log(arr) // [] console.log(arr1) // [] ----------------------------- var arr2 = [1,23,5,6,7]; var arr3 = arr2; arr2 = []; console.log(arr2) // [] console.log(arr3) // [1, 23, 5, 6, 7]
5、改
1)splice
var arr3 = [1,2,3,4,6]; var result = arr3.splice(1,3,"sdf") console.log(result) // [2, 3, 4] 删除的值 console.log(arr3) // [1, "sdf", 6] 删除后插入的值
2)fill
var arr = [1,2,3,4,5,6]; var arr1 = arr.fill(100,1,3); console.log(arr1) // [1, 100, 100, 4, 5, 6]
3)直接通过数组下标
var arr = [1,2,3,4,5,6]; arr[4] = 100 ; console.log(arr); // [1, 2, 3, 4, 100, 6]
6、查
1)indexOf、lastIndexOf:
a、搜索指定元素,返回第一个元素的索引
b、搜索不到则返回 -1
var arr = [1,2,5,6,3,2]; console.log(arr.indexOf(2)); //1
console.log(arr.indexOf(7)); //-1
-