Today we will talk about several methods of operating on arrays:
//Add
a =[];//Empty array
a[0]="I am the first";
a[2]="I am the third";
a[10]="I It is the eleventh one";
alert(a.length);//11
//Delete
var a=[1,2,3,4,5];
delete a[4]//Delete the fifth element, but do not delete the position
alert(a.length);
//Add one at the end of push() or more, and return the new length
a=[1,2,3];
alert(a..push("二狗","男",20));//Add to the end of the array One or more
alert(a.length);
alert(a[0]);
//pop() removes and returns the last element of the array.
//Syntax arr.pop();
//Return value The last element of arr.
var arr=new Array(3);//The length is 3
arr[0]="George";
arr[1]="John";
arr[2]=" Thomas";
document.write(arr)
document.write("
")
document.write(arr.pop())//Delete and return the last item in the array element.
document.write("
")
document.write(arr)
//unshift() Add one or more elements to the beginning of the array, and Return the new length
a=[1,2,3];
a.unshift("二狗","男",20);//Add one or more to the end of the array
alert (a.length);
alert(a[0]);
//shift() delete and return the first element
var arr=new Array(3);
arr[0]="George";
arr[1]="John";
arr[2]="Thomas";
document. write(arr)
document.write("
")
document.write(arr.shift())//Delete and return the first element
document.write("
")
document.write(arr)
//concat() method merges two or more arrays
var a=[1,2,3,4,5];
var b=[6,7,8,9,10];
var c=[11,12,13,14,15 ]
alert(b.concat(a,c));
//join() converts all elements in the array into strings And connected together
var arr=["Today is Friday", "Tomorrow is a holiday", "The day after tomorrow is also a holiday"]
alert(arr.join(","));
alert (typeof arr.join(""))
//revese()The elements are reversed in order
var arr=["Today is Friday", "Tomorrow is a holiday", "The day after tomorrow is also a holiday"];
alert(arr.reverse())
//The slice method intercepts a part of the array,
//The first parameter is the subscript at the beginning of the array, and the corresponding element must be subscripted
//The second parameter is the subscript at the end of the array, but not Corresponding element
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
alert(a.slice (0,10))
alert(a.slice(-15,-5))
alert(a)//Still the original array has not changed
//sort() sorts the array elements
var a=[1,9,5,12,24,16]
function hanshu(x,y){
return x-y;
}
alert(a.sort(hanshu))
//splice( ) is used to insert, delete or replace elements of the original array
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] ;
a.splice(4,6)//Delete 6 starting from the fifth one
alert(a)
a.splice(4,6,50,60,70,80,90,100,110,120,130,140) //Delete 6 numbers starting from the fifth one and add the following numbers
alert(a)
The above is the detailed content of Detailed introduction to methods in arrays. For more information, please follow other related articles on the PHP Chinese website!