Native js study notes 3 - array
Define array
Two ways to define an array:
1. var array1 = new array(1, 2, 3, 4);
2. var array2 = [1, 2, 3, 4];
Insertion and deletion of array elements
• push(element): Add new elements from the end
• unshift(element): Add new elements from the head
• pop(), pop element from the tail
• shift(), pop the element from the head
Delete several elements continuously from a certain position
splice(starting position, length) This method starts from the starting position and deletes length elements
Insertion of array elements Insert several elements
splice(starting position, 0, element to be inserted 1, element to be inserted 2, element to be inserted 3...) Delete 0 elements from the starting position, and then insert the element to be inserted from the starting position Enter array
Replacement of array elements
splice(starting position of the element to be replaced, length of the element to be replaced, newly replaced element 1, newly replaced element 2...)
Sorting of arrays
The sort() method can sort the array (sort according to the order of the ASICC table)
Sort the string array:
var aArray = ["a", "b", "c", "a", "d"];
aArray.sort();
alert(aArray);
Sorting an integer array
Numbers cannot be sorted using the sort() method, so we need to pass a function to the parameter part of the sort method, which has achieved our purpose (this is similar to the meaning of sorting arrays in OC)
var aArray = [2,13,21,12,23,45,23];
aArray.sort(function(num1,num2) {
})
alert(aArray);
Splicing of arrays
The concat() method can realize the splicing of two arrays
var
aArr1 = [1,2,3,4];var
aArr2 = [5,6,7,8];var
aArr3 = aArr1.concat(aArr2);alert(aArr3);
Execution effect:
Add separators between array elements
The join() method can use the parameters in parentheses as element separators in the array
Execution effect: