The array method
Change the original array method:
1, push(): tail add, return value is the changed array length;
var arr = [1, 2]; arr.push(3) ; // 3 arr; // [1, 2, 3] arr.push('b','c'); //5 arr; //[1, 2, 3, "b", "c"] arr. Push ([10,20]); //6 arr; //[1, 2, 3, "b", "c", [10,20]]Copy the code
Pop () is deleted, and the return value is the deleted element.
Var arr =[1, 2, 3, "b", "c", [10,20]]; arr.pop(); //[10, 20] arr; // [1, 2, 3, "b", "c"]Copy the code
The unshift() header returns the changed array length.
var arr = [1, 2]; Arr. Unshift (3, 4); //4 arr; // [3, 4, 1, 2]Copy the code
4. Shift () removes the header and returns the deleted element;
var arr = ['a', 'b', 1, 2];
arr.shift(); //'a'
arr; //['b', 1, 2]
Copy the code
5, sort();
1. The default is to convert all elements to strings, and then sort them by string Unicode code points. The return value is a new array.
var arr = [1, 2, 12, 'a', 'b', 'ab', 'A', 'B'] arr.sort(); / / [1, 12, 2, "A", "B", "A", "ab", "B"] note: 12 ahead of the 2Copy the code
2. If the elements are numbers and you want to sort them from smallest to largest, pass in a callback function as an argument.
var arr = [1, 2, 12, 100]
arr.sort(function(a,b){
return a-b;
});
// [1, 2, 12, 100]
Copy the code
6. Reverse () reverses the position of an element in an array.
var arr = [1, 2, 12, 'a', 'b', 'ab', 'A', 'B'];
arr.reverse();
//["B", "A", "ab", "b", "a", 12, 2, 1]
Copy the code
7, array.splice() intercepts or adds; The return value is the intercepted element
array.splice(index,howmany,item1,….. ,itemX) parameter: index: required pass. Integer to specify where items are added/removed, and negative numbers to specify positions from the end of the array. Howmany: Must pass. Number of items to delete. If set to 0, the project will not be deleted. item1, … , itemX: Optional. The new item added to the array.
1. Only delete, not add. Two arguments can be passed:
var arr = ['Alibaba', 'Tencent', 'Baidu', 'XiaoMi', '360']; // Drop 3 elements from index 2 arr.splice(2, 3); // return the deleted element ['Baidu', 'XiaoMi', '360'] arr; // ['Alibaba', 'Tencent']Copy the code
2. Add but not delete. The second argument is set to 0, that is, no element is deleted.
arr.splice(2, 0, 'Toutiao', 'Meituan', 'Didi'); // Return [], because no element arr is deleted; //["Alibaba", "Tencent", "Toutiao", "Meituan", "Didi"]Copy the code