Add and delete elements in the array js
js array elements in conventional addition method is directly added, push method, and a method unshift
Delete method is to delete, pop, shift
A modification of the method of collection is the splice
1, added:
(1) directly add often the case
was arr = [];
arr[0]="first";
arr[1]="second";
(2)push
Approach is to push the elements to be added to the end, the array length of the array +1
var arr=["first","second"]; //arr.length=2
arr.push("last");// arr→["first","second","last"] arr.length=3
(3)unshift
unshift method is to add an element to be added to the array head, and once the other elements of the index to move higher
var arr=["first","second"]; //arr.length=2
arr.unshift("last");// arr→["last","first","second"] arr.length=3
2, delete
(1)delete
var arr=["first","second","last"];
delete arr[0];//arr→[undefined,"second","last"],arr.length=3;
Not fully achieve the purpose of deleting
(2)pop
pop and push the corresponding method, delete the last element, the array length - 1
var arr=["first","second","last"];
arr.pop();//arr→["first","second"],arr.length=2;
(3)shift
Corresponding to the unshift, delete the first element, the array length - 1, other elements are indexed -1
3、splice
splice method is to modify the method has to add and delete functions
splice () parameter specifies the first two array elements to be deleted, followed by any number of parameters required to specify the elements of the array is inserted, so that splice may be implemented to add, delete, and modify functions. Actually not modify, delete only one element and then inserted back element into that position.
Add to:
was arr = [1,2,3,4,5];
arr.splice(2,0,"change");//arr→[1,2,"change",3,4,5]
2 represents the index parameter, the parameter 0 represents the number of elements to be changed, a parameter representative of the last to be added or replaced inside the element.
delete
arr.splice (2,1); // arr → [1,2,4,5] Of course, a plurality may be deleted, the second parameter to modify