First, the array introduction
Each item of the JavaScript array can hold any type of data, that is, the first position of the array holds the string, the second position can hold the value, the third position can save the object, and the size of the array can be dynamically adjusted, that is, it can grow automatically as the data is added to accommodate the new data.
Ii. operation of arrays
1. Create
Create an empty array var arr = [];var arr2 = [1,true,new Date ()];arr2.length = 2;alert (ARR2); True
2.pop and Push methods
push (): adds one or more elements to the end of the array and returns the new array length.
pop (): Delete the element at the end of the array and return it.
/* PUSH (): Adds one or more elements to the end of the array and returns the new length. * POP (): Delete and return the last element of the array. */var arr = [];var length = Arr.push (1,2,true, "abc"); Alert (arr); 1,2,true,abcalert (length); 4var a = Arr.pop (); alert (arr); 1,2,truealert (a); Abc
3.shift and Unshift methods
shift (): deletes and returns the first element of a numeric value.
unshift (): adds one or more elements to the beginning of the array and returns the new array length.
/* * SHIFT (): Deletes and returns the first element of the array * Unshift (): Adds one or more elements to the beginning of the array and returns the new length. */var arr = [1,true, "abc"];var A = Arr.shift (); alert (a);//1alert (arr);//true,abcvar length = Arr.unshift ("A", "B"); alert (length);//4alert (arr);//a,b,true,abc</script>
4.splice () and slice ()
Splice ()
Explanation: Add/Remove items to/from the array, and then return the deleted content.
Syntax: arr.splice (index,num,item1,item2,..., itemn);
| parameters |
description |
| index |
required. An integer that specifies the position to be manipulated. |
| num |
must. The number to be deleted, if 0, is not deleted. |
| item |
optional. Adds a new item to the array. |
var arr = ["AAA", "BBB", "CCC", "DDD", "EEE"];var newArr = Arr.splice (), alert (NEWARR);//bbbalert (arr);//AAA,CCC,DDD, Eeearr.splice (1,0, "111", "222"); alert (arr); Aaa,111,222,ccc,ddd,eee
Slice ()
Explanation: Returns the selected element to an existing array.
Syntax: arr.slice (start,end);
| Parameters |
Describe |
| Start |
Necessary. Specify where to start the selection. |
| End |
Optional. Specifies where to end the selection. |
Note: This method does not modify the array but returns a sub-array, if you want to delete an element from the array, use Splice ().
var arr = ["AAA", "BBB", "CCC", "DDD", "EEE"];var newArr = Arr.slice (1,3); alert (NEWARR);//bbb,cccalert (arr);//AAA,BBB, Ccc,ddd,eee
JavaScript Basic Learning (iii)-arrays