array
1. Array introduction
An array is also an object
It is similar to our ordinary object function and is also used to store some values
The difference is that ordinary objects use strings as attribute names, while arrays use numbers as index operation elements
Index: the integer starting from 0 is the index
The storage performance of array is better than that of ordinary objects. In development, we often use array to store some data
// Create array object var arr=new Array(); // When typeof is used to check an array, object is returned console.log(typeof arr); // object
Adding elements to an array
Syntax: array [index] = value
arr[0] = 10; arr[1] = 33; arr[2] = 22;
Read elements in array
Syntax: array [index]
If the defined index does not exist, it will not return an error if it is read
console.log(arr[2]); // 22 console.log(arr[3]); // undefined
Gets the length of the array
You can use the length attribute to get the length of the array (number of elements). Syntax: array length
- For continuous arrays, use length to get the length of the array (number of elements)
- For non contiguous arrays, using length will get the maximum index of the array + 1
console.log(arr.length); // 3 console.log(arr); // {"0":10,"1":33,"2":22,"length":3} arr[10] = 33; console.log(arr.length); // 11 console.log(arr); // {"0":10,"1":33,"10":33,"2":22,"length":11}
Try not to create discontinuous arrays
Modify the length of the array
- If the modified length is greater than the original length, the extra part will be empty
- If the modified length is less than the original length, the extra elements will be deleted
arr.length = 100; console.log(arr.length); // 100 console.log(arr); // {"0":10,"1":33,"10":33,"2":22,"length":100} arr.length = 2; console.log(arr.length); // 2 console.log(arr); // {"0":10,"1":33,"length":2}
Adds an element to the last bit of the array
Syntax: array [array. length] = value;
arr[arr.length] = 22; console.log(arr.length); // 3 console.log(arr); // {"0":10,"1":33,"2":22,"length":3} arr[arr.length] = 33; console.log(arr.length); // 4 console.log(arr); // {"0":10,"1":33,"2":22,"3":33,"length":4}
2. How to create an array
Create an array using literals
Syntax: []
var arr1 = []; console.log(arr1); // {"length":0} console.log(typeof arr1); // object console.log(arr1.length); // 0
When you create an array with literals, you can specify the elements in the array at creation time
var arr2 = [1,2,3,4,5,10]; console.log(arr2); // {"0":1,"1":2,"2":3,"3":4,"4":5,"5":10,"length":6} console.log(arr2.length); // 6
Creating arrays using constructors
When using the constructor to create an array, you can also add elements at the same time, and pass the elements to be added as parameters of the constructor
Elements are separated by
var arr3 = new Array(1,2,3,4,5); console.log(arr3); // {"0":1,"1":2,"2":3,"3":4,"4":5,"length":5} console.log(arr3.length); // 5
The difference between literal and constructor when there is only one number
// Create an array in which there is only one element 10 var arr4 = [10]; // Create a number with a length of 10 var arr5 = new Array(10); console.log(arr4.length); // 1 console.log(arr5.length); // 10
3. Array element type
Any data type
Number, string, Boolean, null, undefined
var arr6 = [2, "13", true, null, undefined]; console.log(arr6); // Array(5) // 0: 2 // 1: "13" // 2: true // 3: null // 4: undefined // length: 5
object
// **It can also be an object** var obj = {name:"Sun WuKong"}; var arr7 = []; arr7[arr7.length] = obj; console.log(arr7); // {"0":{"name": "Monkey King"}, "length":1} arr7 = [{name:"Sun WuKong"}, {name:"Sand monk"}, {name:"Zhu Bajie"}]; console.log(arr7); // {"0":{"name": "Monkey King"}, "1":{"name": "sand monk"}, "2":{"name": "pig Bajie"}, "length":3}
function
arr7 = [function(){alert(1)},function(){alert(2)}]; console.log(arr7); // {"0":"function (){alert(1)}","1":"function (){alert(2)}","length":2}
array
Arrays can also be placed in arrays. The following arrays are called two-dimensional arrays
arr7 = [[1,2,3],[4,5,6],[7,8,9]]; console.log(arr7); // {"0":{"0":1,"1":2,"2":3,"length":3},"1":{"0":4,"1":5,"2":6,"length":3},"2":{"0":7,"1":8,"2":9,"length":3},"length":3}
4. Array method
There are many methods of array. Here are some common methods
push()
This method can add one or more elements to the end of the array and return the new length of the array
You can pass the elements to be added as parameters to the method so that they will be automatically added to the end of the array
var result = arr.push("Tang Sanzang"); console.log(arr); // ["Sun Wukong", "pig Bajie", "Sha Wujing", "Tang Sanzang"] arr.push("The Grapes ", "Earth Store Bodhisattva", "Maitreya Buddha"); console.log(arr); // ["Sun Wukong", "pig Bajie", "Sha Wujing", "Tang Sanzang", "Bodhi Laozu", "dizang Bodhisattva", "Maitreya Buddha"] console.log("result = " + result); // result = 4
pop()
This method can delete the last element of the array and return the deleted element as a return value
console.log(arr); // ["Sun Wukong", "pig Bajie", "Sha Wujing", "Tang Sanzang", "Bodhi Laozu", "dizang Bodhisattva", "Maitreya Buddha"] var result = arr.pop(); console.log(arr); // ["Sun Wukong", "pig Bajie", "Sha Wujing", "Tang Sanzang", "Bodhi Laozu", "dizang Bodhisattva"] console.log("result = " + result); // result = Maitreya
unshift()
Adds one or more elements to the beginning of the array and returns the new array length
After the element is inserted forward, the indexes of other elements will be adjusted in turn
console.log(arr); // ["Sun Wukong", "pig Bajie", "Sha Wujing", "Tang Sanzang", "Bodhi Laozu", "dizang Bodhisattva"] result = arr.unshift("Ox demon king", "Erlang God"); console.log(arr); // ["ox demon king", "Erlang God", "Monkey King", "pig Bajie", "Sha Wujing", "Tang Sanzang", "Bodhi Laozu", "Di Zang Bodhisattva"] console.log("result = " + result); // result = 8
shift()
You can delete the first element of the array and return the deleted element as a return value
console.log(arr); // ["ox demon king", "Erlang God", "Monkey King", "pig Bajie", "Sha Wujing", "Tang Sanzang", "Bodhi Laozu", "Di Zang Bodhisattva"] result = arr.shift(); console.log(arr); // ["Erlang God", "Monkey King", "pig Bajie", "shawujing", "Tang Sanzang", "Bodhi ancestor", "dizang Bodhisattva"] console.log("result = " + result); // result = 7
Summary
operation | add to | delete |
---|---|---|
End operation | push: add at the end | pop: delete at the end |
Start operation | unshift: add at the beginning | shift: delete at the beginning |
slice()
Returns the selected element from an existing array, which can be used to extract the specified element from the array
This method does not change the element array, but encapsulates the intercepted elements into a new array and returns the parameters:
- The index of the location where the interception starts, including the start index
- The index at the end of the interception, excluding the end index
result = arr.slice(0,3); console.log(result); // ["Erlang God", "Monkey King", "pig Bajie"]
The second parameter can be omitted without writing. At this time, all elements from the beginning of the index will be intercepted
result = arr.slice(3); console.log(result); // ["Sha Wujing", "Tang Sanzang", "Bodhi Laozu", "dizang Bodhisattva"]
An index can pass a negative value. If a negative value is passed, it is calculated from back to front
- -1 penultimate
- -2 penultimate
result = arr.slice(4, -1); console.log(result); // ["Tang Sanzang", "Bodhi ancestor"]
splice()
Delete the element and add a new element to the array. Can be used to delete a specified element in an array
Using splice() will affect the original array, delete the specified element from the original array, and return the deleted element as a return value
Parameters:
-
First, the index representing the start position
-
The second indicates the number of deleted items
arr = ["Ox demon king", "Erlang God", "Sun WuKong", "Zhu Bajie", "Sha Wujing", "Tang Sanzang", "The Grapes ", "Earth Store Bodhisattva"]; result = arr.splice(0, 2); console.log(result); // ["ox demon king", "Erlang God"] console.log(arr); // ["Sun Wukong", "pig Bajie", "Sha Wujing", "Tang Sanzang", "Bodhi Laozu", "dizang Bodhisattva"] arr = ["Ox demon king", "Erlang God", "Sun WuKong", "Zhu Bajie", "Sha Wujing", "Tang Sanzang", "The Grapes ", "Earth Store Bodhisattva"]; result = arr.splice(1, 2); console.log(result); // ["Erlang God", "Monkey King"] console.log(arr); // ["ox demon king", "pig Bajie", "Sha Wujing", "Tang Sanzang", "Bodhi Laozu", "Di Zang Bodhisattva"]
-
Third and later, you can pass some new elements, which will be automatically inserted in front of the start position index
// Replace element arr = ["Sun WuKong", "Zhu Bajie", "Sha Wujing", "Tang Sanzang"]; result = arr.splice(0, 1, "Ox demon king", "Iron Fan Princess", "Red boy"); console.log(result); // ["Monkey King"] console.log(arr); // ["ox demon king", "Princess Iron Fan", "red boy", "pig Bajie", "Sha Wujing", "Tang Sanzang"] // Insert element arr = ["Sun WuKong", "Zhu Bajie", "Sha Wujing", "Tang Sanzang"]; result = arr.splice(0, 0, "Ox demon king", "Iron Fan Princess", "Red boy"); console.log(result); // [] console.log(arr); // ["ox demon king", "Princess Iron Fan", "red boy", "Monkey King", "pig Bajie", "Sha Wujing", "Tang Sanzang"]
Summary
- slice can extract the specified elements in the array
- splice can delete elements, replace elements and insert elements (more powerful)
concat()
concat() can concatenate two or more arrays and return the new array
This method has no effect on the original array
var arr1 = ["Sun WuKong", "Zhu Bajie", "Sha Wujing"]; var arr2 = ["Green lion monster", "Yellow tooth elephant", "Dapeng golden wing carving"]; var arr3 = ["Tiger power immortal", "Lu Li Daxian", "Yang Li Daxian"]; var arr4 = arr1.concat(arr2,arr3,"Ox demon king","Iron Fan Princess","Red boy"); console.log(arr1); // ["Monkey King", "pig Bajie", "shawujing"] console.log(arr2); // ["green haired lion monster", "yellow toothed old elephant", "Dapeng golden wing carving"] console.log(arr3); // ["tiger power immortal", "deer power immortal", "sheep power immortal"] console.log(arr4); // ["Monkey King", "pig Bajie", "Sha Wujing", "green haired lion monster", "yellow tooth old elephant", "Dapeng golden wing carving", "tiger power immortal", "deer power immortal", "sheep power immortal", "ox demon king", "Iron Fan Princess", "red boy"]
join()
This method can convert the array to a string
This method does not affect the original array, but returns the converted String as the result
In join(), you can specify a string as a parameter, which will become the connector of the elements in the array
If no connector is specified, it is used by default as the connector
var arr = ["Sun WuKong", "Zhu Bajie", "Sha Wujing"]; var result = arr.join(); console.log(arr); // ["Monkey King", "pig Bajie", "shawujing"] console.log(result); // Monkey King, pig Bajie, Sha Wujing console.log(typeof result); // string result = arr.join(""); console.log(result); // Monkey King pig Bajie sand Wujing result = arr.join("@"); console.log(result); // Monkey King @ pig Bajie @ Sha Wujing
reverse()
This method is used to invert the array (the front edge is removed from the rear edge, and the rear edge is removed from the front edge)
This method will directly modify the original array
var arr = ["Sun WuKong", "Zhu Bajie", "Sha Wujing"]; arr.reverse(); console.log(arr); // ["Sha Wujing", "Zhu Bajie", "Sun Wukong"]
sort()
Can be used to sort elements in an array
It will also affect the original array. By default, it will be sorted according to Unicode encoding
var arr = ['f', 'b', 'a', 'h', 'e', 'd']; arr.sort(); console.log(arr); // ["a", "b", "d", "e", "f", "h"]
Even for purely numeric arrays, sorting by sort() is done in Unicode encoding
Therefore, when sorting numbers, you may get wrong results
arr = ['2', '44', '9', '8', '2', '0']; arr.sort(); console.log(arr); // ["0", "2", "2", "44", "8", "9"]
Now we can add a callback function in sort() to specify the sorting rules
Two formal parameters need to be defined in the callback function. The browser will use the elements in the array as arguments to call the callback function
Which element to call is uncertain, but it is certain that a must precede b in the array
The browser will determine the order of elements according to the return value of the callback function,
- If a value greater than 0 is returned, the element swaps positions
- If a value less than or equal to 0 is returned, the element position remains unchanged
arr = [2, 44, 9, 8, 2, 0, 6]; arr.sort(function(a,b){ if(a > b){ return 1; } else { return -1; } }); console.log(arr); // [0, 2, 2, 6, 8, 9, 44]
- Returns a - b if ascending order is required
- If descending order is required, b - a is returned
arr.sort(function(a,b){ // Ascending arrangement return a - b; }); console.log(arr); // [0, 2, 2, 6, 8, 9, 44] arr.sort(function(a,b){ // Descending order return b - a; }); console.log(arr); // [44, 9, 8, 6, 2, 2, 0]
Summary
- Methods that will affect the original array: push, pop, shift, unshift, splice, reverse, sort
- Methods that will not affect the original array: slice, concat, join
- Methods of adding elements: push, unshift, splice
- Methods to delete elements: pop, shift, splice
- Method of replacing elements: splice
- Methods of connecting elements: concat, join
- Sorting method: reverse, sort
5. Array traversal
Normal for loop
The so-called traversal array is to take out all the elements in the array
var arr = ["Sun WuKong", "Zhu Bajie", "Sha Wujing", "White dragon horse"]; // The so-called traversal array is to take out all the elements in the array for(var i=0;i<arr.length;i++){ console.log(arr[i]); }
practice
1. Preparatory work
// Define Person constructor function Person(name, age){ this.name = name; this.age = age; } // Create Person object var per1 = new Person("Sun WuKong", 18); var per2 = new Person("Zhu Bajie", 28); var per3 = new Person("Red boy", 8); var per4 = new Person("spider goblin", 16); var per5 = new Person("Erlang God", 38); // Put these person objects into an array var perArr = [per1, per2, per3, per4, per5]; console.log(perArr); // 0: Person {name: "Monkey King", age: 18} // 1: Person {name: "pig Bajie", age: 28} // 2: Person {name: "red boy", age: 8} // 3: Person {name: "spider spirit", age: 16} // 4: Person {name: "Erlang God", age: 38}
2. Create a function to extract the 18-year-old Person in perArr, package it into a new array and return it
function getAdult(perArr){ // Create a new array var resultArr = []; var person; // Traverse the ARR to get the Person object in the arr for(var i=0;i<perArr.length;i++){ person = perArr[i]; // Judge whether the age of the Person object is greater than or equal to 18 if(person.age >= 18){ // If greater than or equal to 18, this object is added to newArr resultArr.push(person); } } // Return array return resultArr; } var adult = getAdult(perArr); console.log(adult); // 0: Person {name: "Monkey King", age: 18} // 1: Person {name: "pig Bajie", age: 28} // 2: Person {name: "Erlang God", age: 38}
forEach method
Generally, we use the for loop to traverse the array. JS also provides us with a method to traverse the array forEach()
compatibility
This method only supports browsers above IE8, and browsers below IE8 do not support this method
Therefore, if you need to be compatible with IE8, do not use forEach, or use the for loop to traverse
use
The forEach() method requires a function as an argument
Functions like this, which are created by us but not called by us, are called callback functions
If there are several elements in the array, the function will be executed several times. Each time, the browser will traverse the elements
Passed in as arguments, we can define formal parameters to read these contents
parameter
The browser passes three parameters in the callback function:
- The first parameter being traversed is the current element
- The second parameter is the index of the element currently being traversed
- The third parameter is the array being traversed
arr.forEach(function(value, index, obj){ console.log("value = " + value); console.log("index = " + index); console.log("obj = " + obj); });
practice
Array de duplication
// Create an array var arr = [1,2,2,3,2,1,3,4,2,5]; // Remove duplicate numbers from the array // Gets each element in the array for(var i=0;i<arr.length;i++){ // Gets all elements after the current element for(var j=i+1;j<arr.length;j++){ // Determine whether the values of two elements are equal if(arr[i] == arr[j]){ // If equal, it proves that there are duplicate elements, and the corresponding element of j is deleted // arr.splice(j, 1); // When the current j element is deleted, the following element will be filled automatically // At this point, this element will not be compared again. You need to compare the element where j is located again // j--; arr.splice(j--, 1); } } } console.log(arr);