What is an array

An array is a collection of data, each of which is called an element, an elegant way of storing a set of data under the name of a single variable.

Create an array

Create an array using new

varArray name =new Array(a);var arr = new Array(a);// Create a new empty array
var arr = new Array(2);// Create an empty array with two empty elements
var arr = new Array(1.2);Var arr = [1,2]
Copy the code

Use array literals[]Create an array

var arr = [];
var arr1 = [1.2.'hello'.true];// The array can hold any type of data
Copy the code

Gets the elements of an array

Array name [index number]

Through the array

Traversal accesses each element in the array once from beginning to end

The length of the array

Array name. length Dynamically checks the number of array elements

New element in array

Modify length length

var arr=['red'.'yellow'.'green'.'blue'];
console.log(arr.length);
arr.length=5;
console.log(arr[4]);//undefined
Copy the code

Appends an array element to an array index

var arr= ['red'.'yellow'.'green'];
arr[3] = 'blue';/ / append
arr[1] = 'pink';/ / replace
arr = 'hellow world';
console.log(arr);// Hello world assigns the name of the array to be empty
Copy the code

Arrays hold 1 to 10 values

var arr = [];
for (var i=0; i < 10; i++) {
    arr[i]=i;
}
Copy the code

Filter array

Select elements greater than or equal to 8 from the array and put them into the new array

1 / / method.
var arr = [2.9.4.8.4.3.6.5.7.8.9.9];
var newArr = [];
var j=0;
for (var i = 0; i < arr.length; i++) {
    if(arr[i] > 8) {
        newArr[j] = arr[i];
        j++
    }
}
2 / / method.
var arr = [2.9.4.8.4.3.6.5.7.8.9.9];
var newArr = [];
// Newarr.length is 0 at first
for (var i = 0; i < arr.length; i++) {
    if(arr[i] >= 8) { newArr[newArr.length] = arr[i]; }}Copy the code

An array of cases

Arrays are converted to strings

input: [‘red’,’yellow’,’green’,’blue’]

output: ‘red|yellow|green|blue’

var arr=['red'.'yellow'.'green'.'blue'];
var str=' ';
var sep='|';
for(var i=0; i<arr.length; i++){ str += arr[i] + sep; }Copy the code

Flip the array

function reverse(arr) {
    var newArr = [];
    for (var i = arr.length-1; i >= 0; i--) {
        newArr[newArr.length] = arr[i];
    }
    return newArr;
}
console.log(reverse(['red'.'yellow'.'green'.'blue']));
Copy the code

Bubble sort

A simple sorting algorithm repeatedly walks through the sequence to be sorted, comparing two elements at a time, swapping them if they are in the wrong order, and iterating through the sequence until no more swapping is needed.

solution

  • The total number of lies required for the outer for loop
  • The number of times the inner for loop swaps per trip
  • Swap two variables
var arr = [5.4.3.2.1];
for (var i=0; i<arr.length; i++) {
    for (var j=0; j<arr.length-i; j++) {
        if(arr[j] < arr[j+1]) {
            var temp = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temp; }}}Copy the code

Common array methods

Check if it is an array

1.instanceof

var arr = [];
var obj = {};
console.log(arr instanceof Array);//true
console.log(obj instanceof Array);//false
Copy the code

2.Array.isArray()

Added methods supported by Versions later than Internet Explorer 9.

console.log(Array.isArray(arr));//true
console.log(Array.isArray(obj));//false
Copy the code

Gets the array element index

The method name instructions The return value
indexOf() Array to find the first index of a given element Returns the index number if it exists and -1 if it does not
lastIndexOf() The last index in the array Returns the index number if it exists and -1 if it does not
var arr = [10.20.'30'.'xyz'];
arr.indexOf(10); / / 0
arr.indexOf(20); / / 1
arr.indexOf(30); // Element 30 was not found, return -1
arr.indexOf('30'); // Element '30' has an index of 2
Copy the code

Add and remove array elements

Push () and pop ()

  • Add: Push () adds elements to the end of the Array. The return value is the new array length. The original array changes.

  • Delete: pop() removes the last element of the Array. It returns the element that was deleted, the original array changed.

var arr = [1.2];
arr.push('A'.'B'); // Mandatory Array New length: 4
arr; // [1, 2, 'A', 'B']
arr.pop(); // pop() returns 'B'
arr; // [1, 2, 'A']
arr.pop(); arr.pop(); arr.pop(); // Pop 3 times in a row
arr; / / []
arr.pop(); // If an empty array continues to pop, undefined is returned
arr; / / []
Copy the code

Unshift (), and the shift ()

  • Add: The unshift() method adds elements to the Array header. The return value is the new array length. The original array changes.

  • Delete: The shift() method deletes the first element of an Array. It returns the element that was deleted, the original array changed.

var arr = [1.2];
arr.unshift('A'.'B'); // Mandatory Array New length: 4
arr; // ['A', 'B', 1, 2]
arr.shift(); // 'A'
arr; // ['B', 1, 2]
arr.shift(); arr.shift(); arr.shift(); // Shift 3 times
arr; / / []
arr.shift(); Shift does not return an error, instead returning undefined
arr; / / []
Copy the code

Sort an array

sort()

Sort () sorts the current Array and directly changes the positions of elements in the current Array. When called directly, the order is sorted in the default order.

var arr = ['B'.'C'.'A'];
arr.sort();
arr; // ['A', 'B', 'C']

var arr1 = [13.4.77.1.7];
arr1.sort();//🚗 note [1, 13, 4, 7, 77]

var arr1 = [13.4.77.1.7];
arr1.sort(function(a,b) {
    return a-b ;/ / ascending
    //return a-b ; / / descending
})
Copy the code

reverse()

Reverse () reverses the entire Array:

var arr = ['one'.'two'.'three'];
arr.reverse(); 
arr; // ['three', 'two', 'one']
Copy the code

Arrays are converted to strings

toString()

Convert an array to a string, with commas separating each entry.

Join (‘ delimiter ‘)

Converts all elements of an array to a string.

var arr = [1.2.3];
console.log(arr.toString());/ / 1, 2, 3

var arr1 = ['green'.'blue'.'pink'];
console.log(arr1.join());//green,blue,pink
console.log(arr1.join(The '-'));//green-blue-pink
Copy the code

If an Array element is not a string, it is automatically converted to a string and then concatenated.

concat()

The concat() method concatenates the current Array with another Array and returns a new Array:

var arr = ['A', 'B', 'C'];
var added = arr.concat([1, 2, 3]);
added; // ['A', 'B', 'C', 1, 2, 3]
arr; // ['A', 'B', 'C']
Copy the code

The concat() method accepts any element and Array and automatically unwraps the Array and adds them all to the new Array:

var arr = ['A', 'B', 'C'];
arr.concat(1, 2, [3, 4]); // ['A', 'B', 'C', 1, 2, 3, 4] 
Copy the code

slice()

var arr = ['A'.'B'.'C'.'D'];
arr.slice(0.2); / / [0, 2)/' A ', 'B'
arr.slice(2); // From index 3 to end: ['C','D']
Copy the code

splice()

The splice() method is a “universal method” to modify an Array, removing elements from the specified index and then adding elements from that position:

var arr = ['Microsoft'.'Apple'.'Yahoo'.'AOL'.'Excite'.'Oracle'];
// Remove 3 elements from index 2, then add 2 more elements:
arr.splice(2.3.'Google'.'Facebook'); // Return the deleted element ['Yahoo', 'AOL', 'Excite']
arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']
// Delete:
arr.splice(2.2); // ['Google', 'Facebook']
arr; // ['Microsoft', 'Apple', 'Oracle']
// Add, do not delete:
arr.splice(2.0.'Google'.'Facebook'); // Return [], because no elements have been deleted
arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']
Copy the code

An array of cases

Array to heavy

Solution: Iterates through the old array to see if each element in the old array is in the new array. If so, it is not added; if not, it is added to the new array.

function unique(arr) {
    var newArr[];
    for( var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) === -1) {
            newArr.push(arr[i]);
        }
        returnnewArr; }}Copy the code

reference

www.liaoxuefeng.com/wiki/102291…