An array is introduced
An array is a special variable that can hold one or more values.
Create an array
- Using array text
var a = [1, 2, 3, 4]
Copy the code
- use
new
Keyword creation
var a = new Array(1, 2, 3, 4)
Copy the code
Accessing an array element
Access by subscript
var b = a[0]
Copy the code
Changing an array element
a[0]= 5
Copy the code
Length attribute
// access the last element a[a.length-1]Copy the code
Iterate over a set of elements
The for loop
var a = [1, 2, 3, 4]
var sum = 0
for (var i = 0; i < a.length; i++) {
sum += a[i]
}
console.log(sum) // 10
Copy the code
forEach
The forEach() method calls the function (callback) once forEach array element. Takes three parameters: the item value, the item index, and the array itself
var a = [1, 2, 3, 4]
var sum = 0
a.forEach((item, index, self) => {
console.log(item, index, self)
console.log('this', this)
sum = item + 10
})
console.log(sum)
console.log(a)
Copy the code
map
- Create a new array by executing a function on each array element.
- No function is executed on an array element that has no value.
- The original array is not changed.
Takes three parameters: the item value, the item index, and the array itself
var a = [1, 2, 3, 4]
var b = a.map((item, index, self) => {
console.log(item, index, self)
console.log('this', this)
return item + 10
})
console.log(b)
console.log(a)
Copy the code
So you can see thatforEach
与 map
The similarities and differences
Common: – Iterate over groups of numbers – same arguments – this points to window\
The difference: -map returns a value, map() returns a new array and -foreach returns no value; Return undefined. ForEach () will modify the original array
filter
The filter() method creates a new array containing the array elements that pass the test. Takes three parameters: the item value, the item index, and the array itself
var a = [1, 2, 3, 4]
var b = a.filter(item => item > 3)
console.log(b)
Copy the code
reduce
Run the function on each array element to generate (decrement it) a single value. Work from left to right in an array. The original array is not reduced. Accepts three parameters: total (initial/previously returned value), item value, item index, and array itself
var a = [1, 2, 3, 4]
var b = a.reduce((total, item, index, self) => {
return total + item
})
console.log(b)
Copy the code
The reduce() method can accept an initial value
var a = [1, 2, 3, 4]
var b = a.reduce((total, item, index, self) => {
return total + item
}, 100)
console.log(b)
Copy the code
reduceRight()
Similar to Reduce, the difference is that it works from right to left in an array.
every
The every() method checks that all array values pass the test. Takes three parameters: the item value, the item index, and the array itself
some
The some() method checks whether some array values pass the test. Takes three parameters: the item value, the item index, and the array itself
find
The find() method returns the value of the first array element that passes the test function. Takes three parameters: the item value, the item index, and the array itself
var a = [{id: 1, name: 'A'}, {id: 2, name: 'B'}]
var b = a.find(item => item.id == 2)
console.log(b)
Copy the code
findIndex
The findIndex() method returns the index of the first array element that passes the test function.
var a = [{id: 1, name: 'A'}, {id: 2, name: 'B'}]
var b = a.findIndex(item => item.id == 2)
console.log(b)
Copy the code
Array methods
Arrays are converted to strings
toString()
Converts an array to a comma-separated string of array valuesJoin (delimiter)
Method can also combine all array elements into a single string, and delimiters can be defined.
var a = ['A', 'B', 'C', 'D']
var b = a.toString()
var c = a.join(',')
console.log(b) // A,B,C,D
console.log(c) // A,B,C,D
Copy the code
Push – Add elements
The push() method adds a new element to the array (at the end of the array). The push() method returns the length of the new array
var a = ['A', 'B', 'C', 'D']
a.push('E')
console.log(a) // ["A", "B", "C", "D", "E"]
console.log(a.push()) // 5
var b = a.push('F')
console.log(b) // 6
Copy the code
Pop – Removes elements
The pop() method removes the last element from the array.
var a = ['A', 'B', 'C', 'D']
a.pop()
console.log(a) // ["A", "B", "C"]
var b = a.pop()
console.log(b) // C
Copy the code
Displacement of the element
shift
The shift() method removes the first array element and “shifts” all other elements to lower indexes.
var a = ['A', 'B', 'C', 'D']
var b = a.shift()
console.log(b) // A
console.log(a) //["B", "C", "D"]
Copy the code
unshift
The unshift() method ** (at the beginning) adds a new element ** to the array and “inverts” the old element. The unshift() method returns the length of the new array.
var a = ['A', 'B', 'C', 'D']
a.unshift('A+')
console.log(a) // ["A+", "A", "B", "C", "D"]
console.log(a.unshift()) // 5
Copy the code
Splice – Delete, splice
Delete two parameters: start position, delete several items
var a = ['A', 'B', 'C', 'D']
a.splice(2, 2)
console.log(a) // ["A", "B"]
Copy the code
Concatenation parameters: start position, items to delete, elements to add
var a = ['A', 'B', 'C', 'D'] a.splice(2, 2, 'E', 'F', 'G', 'H') console.log(a) // ["A", "B", "E", "F", "G", "H"] / / replace a.s plice (2, 1, 'C'). The console log (a) / / [" a ", "B", "C", "F", "G", "H"]Copy the code
Concat – Array merge
The concat() method creates a new array by merging (joining) existing arrays.
var a = [1, 2, 3]
var b = [4, 5, 6]
console.log(a.concat(b)) // [1, 2, 3, 4, 5, 6]
Copy the code
Slice – Array clipping
The slice() method slices a new array with a fragment of the array. Two parameters: start position, end position (excluding end position elements); If the end position is not set, all remaining elements are intercepted from the start position.
var a = [1, 2, 3, 4, 5]
console.log(a.slice(2, 3))
console.log(a.slice(2))
Copy the code
indexOf
The indexOf() method searches for the element value in the array and returns its position. IndexOf (item, start) The element to retrieve and the starting position (optional). Returns the corresponding subscript if an element is found; Returns -1 if no element is found. Retrieves from the beginning of the array to the end.
LastIndexOf () is similar to indexOf() except that the index is retrieved from the end to the beginning
Sort – Numeric sort
Sort () sorts arrays; Numbers are in ascending order, with letters in alphabetical order.
var a = [6, 1, 2, 8, 4]
console.log(a.sort()) // [1, 2, 4, 6, 8]
var b = ['a', 'g', 'j', 'd', 'c']
console.log(b.sort()) // "a", "c", "d", "g", "j"]
Copy the code
Reverse Reverse () reverses the elements in an array.
var a = [6, 1, 2, 8, 4]
console.log(a.sort().reverse()) // [8, 6, 4, 2, 1]
Copy the code
The ratio of function
The purpose of the comparison function is to define an alternative sort order.
Sort (function(a, b) {return b - a}) console.log(arr) // 1] console.log(arr[0]) Maximum console.log(arr[arr.length-1]) // Minimum // Sort arrays in random order arr.sort(function(a, B){return 0.5 - math.random ()}) console.log(arr) var Max = math.max. Apply (null, Var min = math.min. apply(null, arr) console.log(min) // 1Copy the code