1. Introduction to arrays

JS objects include built-in objects, host objects, and custom objects. An array is also an object, but not just any object.

1, concept,

  • Number: a series of numbers

  • Group: Put together

An array is actually a concept of data structure. Arrays are used to store and index arrays.

Array features:

  1. Arrays have integers whose indexes start at 0.

2. Basic operations on arrays

Create an array

Format:

varArray object =new Array(a);Copy the code

Example:

var arr = new Array(a);console.log("arr: " + arr); // arr: 
Copy the code

Creating an array creates an array object (see reference type), which only opens up memory space, but has no data, so the value is null.

2. Add elements

Format:

Array object [] = element value;Copy the code

Example:

arr[0] = 10;
arr[1] = 20;
Copy the code

Analysis: The above code indicates that 10 is assigned to the first element of the array and 20 to the second element of the array.

3. Access array elements

Format:

Array object []Copy the code

Example:

var arr = new Array(a); arr[0] = 10;
arr[1] = 20;
// Access the arr[0] and arr[1] elements respectively
console.log("arr[0]: " + arr[0]); // arr[0]: 10
console.log("arr[1]: " + arr[1]); // arr[1]: 20
Copy the code

Analysis: Use arr[0] to get the value of the element arr[0] of the array.

4. Get the array length

Format:

Array object.lengthCopy the code

Example:

var arr = new Array(a); arr[0] = 10;
arr[1] = 20;
console.log("Length of ARR:" + arr.length); // Arr length: 2
Copy the code

Analysis: Use arr.length to get the length of the array. The array now has two elements (arr[0], arr[1]), so the length is 2.

5. Change the array length

Format:

Array object. Length = number:Copy the code

Example:

var arr = new Array(a); arr[0] = 10;
arr[3] = 20;
console.log("Length of ARR:" + arr.length); // Arr length: 4
arr.length = 10;
console.log("Length of ARR:" + arr.length); // Arr length: 10
Copy the code

Increase the size of the array. It was originally 4, changed to 10, but the actual assignment is arr[0],arr[3], that is, nothing else is assigned. For example, access the value of arr[7] :

console.log("arr[7]: " + arr[7]);// arr[7]: undefined
Copy the code

When can a value be undefined (only a variable is declared but no value is assigned)?

Notes and Details:

  1. JavaScript does not need to set the length of an array. The length is determined by the number of elements assigned at the time of assignment.
  2. Try not to create non-contiguous arrays.
  3. Unassigned array elements have the value undeifend.

Array literals

Create an array object using array literals

Format:

varArray object = [];Copy the code

Example:

  var arr = [];
Copy the code

Array objects are square brackets []

You can also add values to an array at the same time you create it

2. Use constructors to create arrays as well as add elements

The element to be added is passed as an argument to the constructor

// creates an element with a value of 10
arr = [10];
// Creates an array of length 10
arr = new ( 10);Copy the code

The elements of an array can be any type of data

4. Arrays have four common methods

1, the push ()

Meaning: Push

Adds an element to the end of an array and returns the length of the new array.

Use:

Format:

Array object. Push ([element list]);Copy the code

Example:

var arr = [10.20.30.40.50];
console.log("arr: " + arr);
var result = arr.push("Tang's monk".Bone fairy);
console.log("arr: " + arr);
console.log("result: " + a);
Copy the code

Console output:

arr: 10.20.30.40.50
arr: 10.20.30.40.50Tang Monk white Bone spiritresult: 7
Copy the code

Analysis: Use array objects. Push (element list) can add elements to the end of the array. The push() method returns the length of the new array, which is 7.

2, pop

Removes the last element from the array and returns the last element.

Use:

Format:

Array object. Pop ([element list]);Copy the code

Example:

var arr = [10.20.30.40.50];
console.log("arr: " + arr);
var result = arr.pop();
console.log("arr: " + arr);
console.log("result: " + a);
Copy the code

Console output:

arr: 10.20.30.40.50
arr: 10.20.30.40
result: 50
Copy the code

Select [10,20,30,40] and return 50.

3, unshift ()

Element is the opposite of push()

Adds an element to the top of an array and returns the new array length.

Use:

var arr = [10.20.30.40];
console.log("arr: " + arr);
var result = arr.unshift("java"."python");
console.log("arr: " + arr);
console.log("result: " + result);
Copy the code

Console output:

arr: 10.20.30.40
arr: java,python,10.20.30.40
result: 6
Copy the code

4, the shift ()

The principle is the opposite of pop()

Deletes the first element of an array and returns the first element.

Use:

var arr = [10.20.30.40];
console.log("arr: " + arr);
var result = arr.shift();
console.log("arr: " + arr);
console.log("result: " + result);
Copy the code

Console output:

arr: 10.20.30.40
arr: 20.30.40
result: 10
Copy the code

5. Array traversal

1, concept,

To traverse is to experience again and again, to visit again and again.

To iterate over an array is to pull the elements out of the array

Array traversal method

Method 1: Use a normal for loop to iterate over the array

Format:

for(var i = 0; I < array object.length; i++){console.log(array object [I]); }Copy the code

Example:

var arr =  [10.20.30.40.50];
console.log("arr: " + arr);
for( var i = 0; i<arr.length; i++){
    console.log("arr"+"["+i+"]"+":" + arr[i] );
}
Copy the code

Console output:

arr: 10.20.30.40.50
arr[0] :10
arr[1] :20
arr[2] :30
arr[3] :40
arr[4] :50
Copy the code

Method 2: Use the special foreach() provided by JS to loop through the set of numbers (ie8 + only).

Format:

Array object. ForEach (function(){
    console.log("hello");
});
Copy the code

Example:

var arr =  [10.20.30.40.50];
console.log("arr: " + arr);
arr.forEach(function(){
    console.log("hello");
});
Copy the code

Effect:

Analysis: The number of times forEach() is executed is equal to the number of elements in the array.

3. Three parameters of forEach

With the forEach() method, the browser passes three arguments in the callback function that contain the array’s information.

  • Value: element value of the currently traversed element
  • Index: Index position of the current traversal element
  • Array: array traversed currently
var arr =  [10.20.30.40.50];
console.log("arr: " + arr);
arr.forEach(function(value,index,array){
    console.log("= = = = = = = = = = = = = = = = = = = =");
    console.log('value:' + value);
    console.log("index: " + index);
    console.log("arry: " + array);
});
Copy the code

Console output:

====================
value:10
index: 0
arry: 10.20.30.40.50
====================
value:20
index: 1
arry: 10.20.30.40.50
====================
value:30
index: 2
arry: 10.20.30.40.50
====================
value:40
index: 3
arry: 10.20.30.40.50
====================
value:50
index: 4
arry: 10.20.30.40.50
Copy the code

Callback function: a function created by us but not called by us

6. Array special methods

1, the slice ()

Function: Retrieves the specified element from an array, returning the element. This method does not affect the original array and returns the value as a new array

Format:

Array object. Slice (start position index, end position index);Copy the code

Example:

var arr =  [10.20.30.40.50];
console.log("arr: " + arr);
var result = arr.slice(0.2);
console.log("result: " + result)
Copy the code

Console output:

arr: 10.20.30.40.50
result: 10.20
Copy the code

Analysis: intercepts elements from index 0 to index 2 with values 10,20.

⚠ ️ note ⚠ ️

Slice retrieves elements that contain the start index but not the end index. The principle is that (1,3) is actually [1,3] the mathematical “open before closed” principle. You get 1, but you don’t get 3.

2, splice ()

Action: You can delete a range element and add a new element.

Method 1: Only two parameters

Format:

Array object.splice (location index to start deletion, location index to end deletion)Copy the code

Example:

var arr = ["Pig Eight Quit"."Sun Wukong"."Sand monk".The Bull King];
var result = arr.splice(0.3);
console.log("result: " + result);
console.log("arr: " + arr);
Copy the code

Console output:

Result: Pig Bajie, Sun Wukong, Sand MonkarrBut the king bull:Copy the code

Analysis: delete from index 0 to index 3(excluding index 3 elements) namely Pig eight Quit, Sun Wukong, Sand Monk. The only element left after the deletion is the “Bull Demon king” element.

Method 2: Three parameters

Format:

Array object.splice (position index at the beginning of deletion, position index at the end of deletion, new element added to array after deletion)Copy the code

Example:

var arr = ["Pig Eight Quit"."Sun Wukong"."Sand monk".The Bull King];
var result = arr.splice(0.3.Princess Iron Fan);
console.log("result: " + result);
console.log("arr: " + arr);
Copy the code

Console output:

Result: Pig Bajie, Sun Wukong, Sand MonkarrPrincess Iron Fan, Bull Demon kingCopy the code

Splice () = splice(); splice() = splice(); splice();

Three parameters are described:

1.Starts to drop the element's location index2.The number of elements to be deleted starting with the first element3.Adds the element to the top of the deleted arrayCopy the code

🔊 prompt 🔊

The second parameter b in splice(a,b,c) is the number of elements removed from the first parameter a. [A,b].

For the index and element mapping of the array, see: XXX

7. Array residual method

1, the concat ()

Connect two or more arrays and return a new array. Does not affect the original array; Must put in a new array

🚀T- Tests using concat to join two arrays.

var arr1 = ["Sun Wukong"."Pig Eight Quit"."Sand monk"];
var arr2 = [Bone fairy."Spider spirit"."狐狸精"];

// Start connecting ARR1 and ARR2
var result = arr1.concat(arr2);
console.log("result: " + result);
Copy the code

Console output:

Result: Sun Wukong, Zhu Bajie, Sand monk, Bone essence, spider essence, fox essenceCopy the code

Analysis: The connection here is relative to ARR1, to connect arR2, the form is “ARR1 + ARR2”. So you end up with ARr1 first and arR2 second.

🚀T- Tests using concat to join multiple arrays.

var arr = ["Sun Wukong"."Pig Eight Quit"."Sand monk"];
var arr2 = [Bone fairy."Spider spirit"."狐狸精"];
var arr3 = [The Jade Emperor.Princess Iron Fan.Red Boy];
var result = arr.concat(arr2,arr3);
console.log("result: " + result);
Copy the code

Console output:

result: ["Sun Wukong"."Pig Eight Quit"."Sand monk".Bone fairy."Spider spirit"."狐狸精".The Jade Emperor.Princess Iron Fan.Red Boy]
Copy the code

Analysis: Again, the form is “arr + arR2 + arr3”.

2, the join ()

Function: Array to string (take the value of an array element as a string); Does not affect the original array; Join () takes a string as an argument, called a concatenate to join array elements.

Format:

Array object.join ("Element before separator");
Copy the code

Example:

var arr1 = ["Sun Wukong"."Pig Eight Quit"."Sand monk"];
var result = arr1.join("-");
console.log("result: " + result);
console.log( typeof result );
Copy the code

Console output:

Result: Sun Wukong -- Pig Eight Quit -- Sha Seng stringCopy the code

Parses: Concatenates each element of an array with the specified string. And the number result is a string, not an array.

3, reverse ()

Function: This method reverses an array (front to back, back to front); This method modifies the original array

var arr1 = ["Sun Wukong"."Pig Eight Quit"."Sand monk"];

var result = arr1.reverse();        
console.log("result: " + result);
console.log("arr1: " + arr1);
Copy the code

Console output:

Result: Sha Seng, Zhu Bajie, Sun Wukongarr1: Sand monk, Pig Eight Jie, Sun WukongCopy the code

4, the sort ()

Sort an array element; Affects the original array, which is sorted in Unicode code order by default. For numeric arrays, sorting by sort () also results in incorrect results when sorting numbers in the order of the Unicode table

Custom collation rules

You can specify callback functions in sort() to define rules

For example, specify two arguments in a callback function. The browser uses a callback function that takes array elements as arguments.

var arr = [5.4.0.9.3.2.8.7.1.6];

arr.sort(function(a,b){
    // if a > b
    if(a > b){
        return 1;
    }else if(a < b){
        return -1;
    }else{
        return 0; }});console.log(arr);
Copy the code

Analysis: The above algorithm implementation is ascending sort.