“Code Tailor “provides technology related information and a series of basic articles for front-end developers. Follow the wechat public account” Rookie of Xiaohe Mountain “to get the latest articles.
preface
Before we get started, we want to let you know that this article is a summary of the “arrays” section of the JavaScript language. If you already know the following, you can skip this section and jump right into the exercises
- Introduction of the array
- Define an array
- Array assignment and use
- Common methods of arrays
- Array traversal
If you are a little bit forgotten about some parts, 👇🏻 is ready for you!
Summary to summarize
Introduction of the array
Array is a very common type in ECMAScript. ECMAScript arrays are very different from arrays in other programming languages. Like arrays in other languages, ECMAScript arrays are an ordered set of data, but unlike arrays in other languages, each slot in the array can store any type of data. This means that you can create an array whose first element is a string, whose second element is a value, and whose third element is an object. ECMAScript arrays are also dynamically sized and grow automatically as data is added.
Define an array
There are several basic ways to create arrays. One is to use the Array constructor, for example:
let colors = new Array(a)Copy the code
If you know the number of elements in the array, you can pass a value to the constructor, and the Length attribute is automatically created and set to that value. For example, the following code creates an array with an initial length of 20:
let colors = new Array(20)
Copy the code
You can also pass elements to the Array constructor to save. For example, the following code creates an array of three string values:
let colors = new Array('red'.'blue'.'green')
Copy the code
You can pass a value to the constructor when creating an array. This is a bit of a problem, because if the value is a number, an array of the specified length is created; If the value is of any other type, an array is created containing only that particular value. Here’s an example:
let colors = new Array(3) // Create an array of three elements
let names = new Array('Greg') // Create an array containing only one element, the string "Greg"
Copy the code
You can also omit the new operator when using the Array constructor. The results are the same, for example:
let colors = Array(3) // Create an array of three elements
let names = Array('Greg') // Create an array containing only one element, the string "Greg"
Copy the code
Another way to create arrays is to use array literal notation. Array literals are comma-separated lists of elements enclosed in brackets, as shown in the following example:
let colors = ['red'.'blue'.'green'] // Create an array of three elements
let names = [] // Create an empty array
let values = [1.2] // Create an array of 2 elements
Copy the code
In this example, the first line creates an array of three strings. The second line creates an empty array with a pair of air parentheses.
The third line shows the effect of putting a comma after the last value of an array: Values is an array of two values (1 and 2).
Array assignment and use
To get or set the value of an array, use brackets and provide a numeric index of the corresponding value, as shown below:
let colors = ['red'.'blue'.'green'] // Define an array of strings
console.log(colors[0]) // Display the first item
colors[2] = 'black' // Modify the third item
colors[3] = 'brown' // Add the fourth item
Copy the code
The index provided in brackets represents the value to be accessed. If the index is less than the number of elements contained in the array, the element stored in the corresponding location is returned, just as colors[0] shows red in the example. You set the value of the array in the same way, by replacing the value at the specified location. If you set a value to an index that exceeds the maximum index of the array, as in the example colors[3], the array length automatically expands to that index value plus 1 (the index set in the example is 3, so the array length becomes 4). The number of elements in the array is stored in the Length attribute, which always returns a value of 0 or greater, as shown in the following example:
let colors = ['red'.'blue'.'green'] // Create an array of three strings
let names = [] // Create an empty array
console.log(colors.length) / / 3
console.log(names.length) / / 0
Copy the code
The array Length property is unique in that it is not read-only. You can remove or add elements from the end of an array by modifying the Length attribute. Consider the following example:
let colors = ['red'.'blue'.'green'] // Create an array of three strings
colors.length = 2
console.log(colors[2]) // undefined
Copy the code
Here, the array colors starts with three values. Setting length to 2 removes the last value (in position 2), so colors[2] has no value. If length is set to a value greater than the number of elements in the array, the newly added elements will be filled with undefined, as shown in the following example:
let colors = ['red'.'blue'.'green'] // Create an array of three strings
colors.length = 4
console.log(colors[3]) // undefined
Copy the code
Here we set the length of the array colors to 4, even though the array contains only three elements. Position 3 does not exist in the array, so accessing its value returns the special value undefined. Using the Length attribute makes it easy to add elements to the end of an array, as shown in the following example:
let colors = ['red'.'blue'.'green'] // Create an array of three strings
colors[colors.length] = 'black' // Add a color (position 3)
colors[colors.length] = 'brown' // Add another color (position 4)
Copy the code
The index of the last element in the array is always Length-1, so the index of the next new slot is Length. Each time you add an item after the last element in the array, the array’s Length property is automatically updated to reflect the change. This means that the second line colors[colors.length] adds a new element at position 3, and the next line adds a new element at position 4. The new length is automatically updated when the new element is added to a location outside the current array. In other words, the length property is updated to position plus 1, as shown in the following example:
let colors = ['red'.'blue'.'green'] // Create an array of three strings
colors[99] = 'black' // Add a color (position 99)
console.log(colors.length) / / 100
Copy the code
Here, the Colors array has a value inserted into position 99, resulting in a new length of 100(99 + 1). All of the elements in between, positions 3 through 98, don’t actually exist, so undefined is returned when accessed.
Common methods of arrays
1.Array.join()
The join() method is used to put all the elements of an array into a single string. The join() method can pass in a delimiter by which elements are separated; otherwise, the default is comma.
let Array = ['apple'.'banner'.'cat']
let joinArray1 = Array.join(' ')
console.log(joinArray1) // 'apple banner cat'
let joinArray2 = Array.join(The '-')
console.log(joinArray2) // 'apple-banner-cat'
let joinArray3 = Array.join()
console.log(joinArray3) // 'apple,banner,cat'
Copy the code
2.Array.pop()
The pop() method removes and returns the last element of the array. The pop() method removes the last element of the arrayObject, reduces the array length by one, and returns the value of the element it removed. If the array is already empty, pop() does not change the array and returns undefined.
let Array = ['apple'.'banner'.'cat']
let popArray = Array.pop()
console.log(popArray) // 'cat'
console.log(Array) //[ 'apple', 'banner' ]
Copy the code
3.Array.push()
The push() method adds one or more elements to the end of the array and returns a new length. The push() method adds its arguments sequentially to the end of the arrayObject. It modifies the arrayObject directly, rather than creating a new array. The push() and pop() methods use the in-and-out functionality provided by arrays.
let Array = ['apple'.'banner'.'cat']
let pushArray1 = Array.push('dog')
console.log(pushArray1) / / 4
console.log(Array) // [ 'apple', 'banner', 'cat', 'dog' ]
let pushArray2 = Array.push('egg'.'fox')
console.log(pushArray2) / / 6
console.log(Array) // [ 'apple', 'banner', 'cat', 'dog', 'egg', 'fox' ]
Copy the code
4.Array.reverse()
The reverse() method is used to reverse the order of elements in an array. And this method changes the original array rather than creating a new one. The return value of this function is a pointer to the array.
let Array = ['apple'.'banner'.'cat']
let reverseArray = Array.reverse()
console.log(reverseArray) // [ 'cat', 'banner', 'apple' ]
console.log(Array) // [ 'cat', 'banner', 'apple' ]
console.log(reverseArray === Array) // true
Copy the code
5.Array.shift()
The shift() method removes the first element from an array and returns the value of the first element. If the array is empty, the shift() method does nothing and returns undefined. Instead of creating a new array, this method directly modifies the existing arrayObject.
let Array = ['apple'.'banner'.'cat']
let shiftArray = Array.shift()
console.log(shiftArray) // 'apple'
console.log(Array) // [ 'banner', 'cat' ]
Copy the code
6.Array.unshift()
The unshift() method adds one or more elements to the beginning of the array and returns the new length. The unshift() method inserts its arguments into the head of the arrayObject and moves the existing elements sequentially to the higher subscript to leave space. The first argument to the method will be the new element 0 of the array, if there is a second argument, it will be the new element 1, and so on.
let Array = ['apple'.'banner'.'cat']
let unshiftArray1 = Array.unshift('rookies')
console.log(unshiftArray1) / / 4
console.log(Array) // [ 'xhs', 'apple', 'banner', 'cat' ]
let unshiftArray2 = Array.unshift('hello'.'xhs')
console.log(unshiftArray2) / / 6
console.log(Array) // [ 'hello', 'xhs', 'rookies', 'apple', 'banner', 'cat' ]
Copy the code
7.Array.slice()
The slice() method returns selected elements from an existing array. Returns a new array containing elements from the arrayObject from start to end (excluding the element). You can use negative values to pick elements from the end of the array. If end is not specified, the slice() method selects all elements from start to the end of the array.
let Array = ['apple'.'banner'.'cat']
let sliceArray1 = Array.slice(0.2)
console.log(sliceArray1) // [ 'apple', 'banner' ]
console.log(Array) // [ 'apple', 'banner', 'cat' ]
let sliceArray2 = Array.slice(-2, -1)
console.log(sliceArray2) // [ 'banner' ]
let sliceArray3 = Array.slice(1)
console.log(sliceArray3) // [ 'banner', 'cat' ]
let sliceArray4 = Array.slice(-1)
console.log(sliceArray4) // [ 'cat' ]
Copy the code
8.Array.splice()
The splice() method modifies an array by deleting or replacing existing elements or adding new ones in place, and returns the modified contents as an array. This method changes the original array. The splice() method removes zero or more elements starting at index and replaces those deleted elements with one or more values declared in the argument list. If an element is deleted from an arrayObject, an array containing the deleted element is returned.
let Array = ['apple'.'banner'.'cat']
// Just fill in the first and second arguments to delete the elements in the array and return the array of deleted elements
let spliceArray1 = Array.splice(1.1)
console.log(spliceArray1) // [ 'banner' ]
console.log(Array) // [ 'apple', 'cat' ]
// If the second argument is written to 0, it will not be deleted
let spliceArray2 = Array.splice(1.0)
console.log(spliceArray2) / / []
console.log(Array) // [ 'apple', 'cat' ]
// If there are more than two arguments, the element will be added at the starting position after the deletion
let spliceArray3 = Array.splice(1.1.'hello'.'xhs')
console.log(spliceArray3) // [ 'cat' ]
console.log(Array) // [ 'apple', 'hello', 'xhs' ]
Copy the code
Array traversal
There are many ways to traverse an array. Here are some of the more common ways to traverse an array
1. The for loop
let array = [1.2.3.4.5]
for (let i = 0; i < array.length; i++) {
console.log(array[i])
}
/ / 1
/ / 2
/ / 3
/ / 4
/ / 5
Copy the code
2. for… in…
for… in… It iterates through the index value of all the data in the array and retrieves the value of each index.
let array = [1.2.3.4.5]
for (let i in array) {
console.log(array[i])
}
/ / 1
/ / 2
/ / 3
/ / 4
/ / 5
Copy the code
3. forEach()
Each array has a forEach function, which takes a callback that calls the value of the array each time until the loop is completed.
let array = [1.2.3.4.5]
array.forEach(function (item) {
console.log(item)
})
/ / 1
/ / 2
/ / 3
/ / 4
/ / 5
Copy the code
The title self-test
One: What does the following code output
const numbers = [1.2.3]
numbers[10] = 11
console.log(numbers)
Copy the code
- A:
[1, 2, 3, 7 x null, 11]
- B:
[1, 2, 3, 11]
- C:
[1, 2, 3, 7 x empty, 11]
- D:
SyntaxError
Answer
Answer: C
Numbers [10]=11 makes the length of the array 11, and only the elements with indexes 0, 1, 2, and 10 have values. The middle element is empty, printed as empty in the array, and is undefined when accessed as an element.
Two: What does the following code output
let array = [1.2.3.4.5]
array.length = 3
array[3] = array[3] * 2
let num = ' '
for (let i in array) {
num += array[i]
}
console.log(num)
Copy the code
- A:
1238
- B:
14
- C:
9
- D:
123NaN
Answer
Answer: D
Array =[1,2,3]; when array[3] is accessed, undefined, undefined*2 gets NaN. So array now becomes [1,2,3,NaN]. Num is initialized to a string, so traversal is a string concatenation of all elements, and 123NaN is output
Three: What is the output of the following code execution
let array1 = [1.2.3.4.5]
let array2 = array1
array2[2] = 5
array1[3] = 6
let num = 0
for (let i in array1) {
num += array2[i]
}
console.log(num)
Copy the code
- A:
15
- B:
16
- C:
19
- D:
012565
Answer
Answer: C
Since array2=array1, using array1 and array2 to point to the same array is modified to become [1,2,5,6,5]. After summation, the answer is 19
JavaScript series array, we end here, thank you for your support to the author! Your attention and praise will be the strongest motivation for us to move forward! Thank you!