Each slot in the ECMAScript Array can store any type of data.
The basic concept
Create an array
Created from the Array constructor
let colors=new Array(a)let colors=new Array(10) // A number can be passed to indicate the number of elements in the array
let colors=new Array("red"."green"."yellow") // The saved element can be passed in
Copy the code
Created by literals
let colors=[]
let colors=["red"."green"."yellow"]
Copy the code
An array of space
You can use a string of commas to create a space.
let arr=[,,,,,]
Copy the code
The ES6 new method generally treats the vacancy as an existing element, with a value of undefined
The index and the length
To get or set the value of an array, use the positional index corresponding to the element using brackets:
let colors=["red"."green"."yellow"]
console.log(colors[0]) // Display the first item
colors[2] ="blue" // Modify the third item
colors[3] ="orange" // Add the fourth item
Copy the code
Length is an array property, representing the number of elements in the array. We can delete or add elements to an array by changing length:
let colors=["red"."green"."yellow"]
colors.length=2 / / delete
console.log(colors[2]) //undefined
colors.length=4 // add, new elements are filled with undefined
Copy the code
The index of the last element of the array is always Length-1, and using length makes it easy to add a new element to the end:
let colors=["red"."green"."yellow"]
colors[colors.length]="blue"
colors[colors.length]="black"
Copy the code
Detection array
Instanceof can be used when there is only one global scope:
let something=[1.2]
console.log(something instanceof Array)
Copy the code
If the page has multiple global execution contexts, there will be different versions of the Array constructor. Using array.isarray () eliminates these concerns:
let something=[1.2]
console.log(Array.isArray(something))
Copy the code
conversion
Convert to an array
Array.from()
Is used toClass array structureConvert to an array instanceArray.from("Matt") //["M","a","t","t"] // You can take the second argument to operate on the converted array Array.from([1.2.3].x= >x**2) / /,4,9 [1] Copy the code
Class array structure: any iterable structure; Or structure with a length attribute and cocoa index element
Array.of()
Use to convert a set of parameters to an array instanceArray.of(1.2.3.4) / / [1, 2, 3, 4] Copy the code
Convert to string
toString()
(Do not change the original array)toLocaleString()
(Do not change the original array)Join (separator)
: the default with.
Separate elements. (Do not change the original array)let arr=["red"."green"."yellow"] arr.toString() //red,green,yellow arr.toLocaleString() //red,green,yellow arr.join() //red,green,yellow arr.join("| |") //red||green||yellow Copy the code
If an item in the array is null or undefined, these methods return the result as an empty string
Instance methods
Add and remove elements
-
Push (element) : Adds elements to the end of the array
-
Unshift (element) : Adds elements to the beginning of the array
-
Pop () : Removes the last item of the array, returning the deleted element
-
Shift () : Removes the top item of the array, returning the deleted element
let colors=new Array() colors.push("red") // Print colors: ["red"] colors.push("blue") // Print colors: ["red","blue"] colors.unshift("green") // Print colors: ["green","red","blue"] colors.pop() // Print colors: ["green","red"] colors.shift() // Print colors: ["red"] Copy the code
Operating an array
-
Concat (element) | array: acceptable element or an array, the stitching at the end of the array. (Do not change the original array)
let colors=["red"."green"."yellow"] colors.concat("black"["pink"."orange"]) //["red","green","yellow","black","pink","orange"] Copy the code
-
Slice: Extracts elements from the start to the end to form a new array. (Do not change the original array)
let colors=["red"."green"."yellow"."black"] colors.slice(1) //["green","yellow","black"] truncates the end of the index without ending it colors.slice(1.3) //["green","yellow"] Copy the code
-
Splice (start index, number to remove, element) : Delete, insert, and replace arrays.
// Delete: you need to pass in the first two arguments let colors=["red"."green"."yellow"."black"] colors.splice(1.1) // Print colors: ["red","yellow","black"] // Replace: the first, second, and third arguments need to be passed. The number of the second argument should correspond to the number of elements let colors=["red"."green"."yellow"."black"] colors.splice(1.1."pink") // Replace - Print colors: ["red","pink","yellow","black"] // Add: the first, second, and third parameters need to be passed. The number of the second argument is 0 colors.splice(1.0."pink") / / add - print colors: [" red ", "pink", "green", "yellow", "black"] Copy the code
Sorting method
reverse()
: Reverse sortlet arr=[1.2.3.4.5] arr.reverse() // print arr: [5,4,3,2,1] Copy the code
sort()
: Sort the data in ascending order by default. That is, the minimum is first, and the maximum is second. Sort is called on every itemString()
Transform the function, and then compare the strings.let arr=[2.10.9.5] arr.sort() // print arr: [10,2,5,9] Copy the code
Due to the
sort()
It’s sorted by string, so it’s not applicable in many cases. To this end,sort()
Can accept oneThe comparison functionIs used to determine which value should be ranked first. The comparison function takes two arguments and returns a negative value if the first argument should come first. Returns 0 if it is equal, and a positive value if the first argument should come after the second. Here is a comparison function:function compare(value1,value2){ if(value1<value2){ return -1 }else if(value1>value2){ return 1 }else{ return 0}}let arr=[2.10.9.5] arr.sort(compare) // print arr: [2,5,9,10] Copy the code
The above example can be abbreviated as:
let arr=[2.10.9.5] arr.sort((a,b) = >a<b?1:a>b? -1:0) // print arr: [2,5,9,10] arr.sort((a,b) = >a-b) // print arr: [2,5,9,10] Copy the code
The search method
-
IndexOf: Searches from the front and returns the index position of the element, or -1 if not found
-
LastIndexOf: Searches from behind and returns the index position of the element, or -1 if not found
-
Includes: Search from the front, return true if found, false otherwise
let num=[1.2.3.4.5.4.3.2.1] num.indexOf(4) / / 3 num.lastIndexOf(4) / / 5 num.includes(4) //true num.indexOf(4.4) / / 5 num.lastIndexOf(4.4) / / 3 num.includes(4.7) //false Copy the code
The above three methods compare parameters with elements of each item of the array in strict equality mode, that is, ===
-
Find: Returns the first matched element (without changing the original array)
-
FindIndex (function) : Returns the index of the first matched element. If no one is found, -1 is returned
let people=[ {name:"Xiao Ming".age:17}, {name:"Li hua".age:27},]let result=people.find(item= >item.age>18) / / {" name ":" li hua ", "age" : 27} let result2=people.findIndex(item= >item.age>18) / / 1 Copy the code
The function passed in takes three arguments: the element, the index, and the array itself. An assertion function is considered a match when its return value is true
Iterator method
In ES6, the Array prototype exposes three methods for retrieving the contents of an Array:
keys()
: Returns an arrayThe indexThe iteratorvalues()
: Returns an arrayThe elementThe iteratorentries()
: Returns an arrayKey/value pairThe iteratorlet arr=["red"."green"."yellow"."blue"] Array.from(arr.keys()) / /,1,2,3 [0] Array.from(arr.values()) //["red","green","yellow","blue"] Array.from(arr.entries()) //[[0,"red"],[1,"green"],[2,"yellow"],[3,"blue"]] Copy the code
An iterative approach
-
Every (function, scoped object) : Runs a function on each item of the array, and returns true if each item returns true
-
Some (function, scoped object) : Runs a function on each item of the array, returning true if one of the items returns true
-
Filter (function, scoped object) : Runs a function on each item of the array, forming a new array of the items that return true and returning (unchanged) the original array
-
Map (function, scoped object) : Runs the function on each item of the array, returns the new array after calling the function (without changing the original array)
-
ForEach (function, scoped object) : Runs a function on each item of the array, with no return value. Essentially the equivalent of a for loop (without changing the array)
The function passed in takes three arguments: the element, the index, and the array itself
let num=[1.2.3.4.5.4.3.2.1] num.every(item= >item>2) //false num.some(item= >item>2) //true num.filter(item= >item>2) / /,4,5,4,3 [3] num.forEach(item= >Operation)Copy the code
Merge method
Reduce (function, merge starting point)
: Iterates through all items from the front and builds a final return value based on thatReduceRight (function, merge starting point)
: Iterates through all items from the back to the front, and builds a final return value based on that
The function passed in takes four arguments: the previous merge value, the current item, the current item index, and the array itself. Any value returned by this function becomes the first argument of the next call.
let num=[1.2.3.4.5] let result=num.reduce((prev,cur,index,array) = >{ return prev+cur }) console.log(result) / / 15 Copy the code
Copy and fill
Fill (fill content, start index, end index)
: in the givenThe index range,Fill the contentOverwrite the original contentlet arr=[0.0.0.0.0] arr.fill(5) // Print arR: [5,5,5,5] arr.fill(5.3) // print arr: [0,0,0,5,5] arr.fill(5.1.3) // print arr: [0,5,5,0,0] arr.fill(5.3.10) // print arr: [0,0,0,5,5] populates only existing parts, no expansion arr.fill(5.10.15) // prints arr: [0,0,0,0,0] beyond array bounds, ignored arr.fill(5.4.2) // Print arr: [0,0,0,0] in the opposite direction and ignore Copy the code
CopyWithin (overwrite index, start index, end index)
: copies the given firstThe index rangeThe elements in the original array will then be copied from the contentsCover indexBegan to coverlet arr=[0.1.2.3.4.5.6.7.8.9] arr.copyWithin(5) // Prints arr: [0,1,2,3,4,0,1,2,3,4] If no index is started, the index starts from 0 to the end arr.copyWithin(0.5) // print arr: [5,6,7,8,9,5,6,7,8,9] arr.copyWithin(4.0.3) // print arr: [0,1,2,3,0,1,2,7,8,9] arr.copyWithin(4.12.15) // prints arr: [0,1,2,3,4,5,6,7,8,9] out of bounds, ignored arr.copyWithin(4.4.2) // print arr: [0,1,2,3,4,5,6,7,8,9] in the opposite direction and ignore arr.copyWithin(4.7.12) // print arr: [0,1,2,3,7,8,9,7,8,9] only the existing parts are copied Copy the code
The original array cannot be scaled in this way. For parameters, if there is a start index and an end index, it starts from the start index and ends before the end index (that is, the end index is not included)