3
头图
"Code tailor" provides technical-related information and a series of basic articles for front-end developers. Follow the "Novices of Xiaohe Mountain" public account on WeChat to get the latest articles in time.

Preface

Before you start learning, what we want to tell you is that this article is a JavaScript "array" in 060a5c2ab72704 language knowledge. If you have mastered the following knowledge items, you can skip this section and directly enter the exercise

  • Introduction to arrays
  • Define the array
  • Array assignment and use
  • Common methods of arrays
  • Array traversal

If you have forgotten some parts, 👇🏻 is ready for you!

Summary

Introduction to arrays

Array ( Array ) is a very commonly used type ECMAScript ECMAScript array is very different from arrays in other programming languages. Like arrays in other languages, the ECMAScript array is also a set of ordered data, but unlike 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, the second element is a number, and the third is an object. ECMAScript array is also dynamically sized and will automatically grow as data is added.

Define the array

There are several basic ways to create an array. One is to use the Array constructor, such as:

let colors = new Array()

If you know the number of elements in the array, you can pass a value to the constructor, and then the length attribute will be automatically created and set to this value. For example, the following code creates an array 20 length is 060a5c2ab728ee:

let colors = new Array(20)

You can also pass in the elements to be saved Array For example, the following code creates an 3 string values:

let colors = new Array('red', 'blue', 'green')

You can pass a value to the constructor when creating an array. There is a problem at this time, because if the value is a numeric value, an array with a length of the specified value will be created; and if the value is of other types, an array containing only the specific value will be created. Let's look at an example:

let colors = new Array(3) // 创建一个包含 3 个元素的数组

let names = new Array('Greg') // 创建一个只包含一个元素,即字符串"Greg"的数组

When using the Array constructor, you can also omit the new operator. The result is the same, such as:

let colors = Array(3) // 创建一个包含 3 个元素的数组

let names = Array('Greg') // 创建一个只包含一个元素,即字符串"Greg"的数组

Another way to create an array is to use the array literal ( array literal ) notation. An array literal is a comma-separated list of elements enclosed in square brackets, as shown in the following example:

let colors = ['red', 'blue', 'green'] // 创建一个包含 3 个元素的数组

let names = [] // 创建一个空数组

let values = [1, 2] // 创建一个包含 2 个元素的数组

In this example, the first line creates an 3 strings. The second line creates an empty array with a pair of air brackets.

The third line shows the effect of adding a comma after the last value of the array: values is an array containing two values ( 1 and 2 ).

Array assignment and use

To get or set the value of an array, you need to use square brackets and provide the numeric index of the corresponding value, as shown below:

let colors = ['red', 'blue', 'green'] // 定义一个字符串数组

console.log(colors[0]) // 显示第一项

colors[2] = 'black' // 修改第三项

colors[3] = 'brown' // 添加第四项

The index provided in square brackets indicates the value to be accessed. If the index is less than the number of elements in the array, the element stored in the corresponding position is returned, just like colors[0] shows red example. The method of setting the value of an array is the same, which is to replace the value at the specified position. If you set a value to an index that exceeds the maximum index of the array, like colors[3] in the example, the array length will automatically expand to the index value plus 1 3 is set in the example, so the array length becomes 4 ). The number of elements in the array is stored in the length attribute, which always returns 0 or a value greater than 0 , as shown in the following example:

let colors = ['red', 'blue', 'green'] // 创建一个包含 3 个字符串的数组

let names = [] // 创建一个空数组

console.log(colors.length) // 3

console.log(names.length) // 0

The unique feature of the array length attribute is that it is not read-only. By modifying the length attribute, you can delete or add elements from the end of the array. Consider the following example:

let colors = ['red', 'blue', 'green'] // 创建一个包含 3 个字符串的数组

colors.length = 2

console.log(colors[2]) // undefined

Here, the array colors initially has 3 values. Setting length to 2 will delete the last 2 ), so colors[2] has no value. If length set to a value greater than the number of elements in the array, all newly added elements will be undefined , as shown in the following example:

let colors = ['red', 'blue', 'green'] // 创建一个包含 3 个字符串的数组

colors.length = 4

console.log(colors[3]) // undefined

Here the array colors of length set 4 , although the array contains only 3 elements. The position 3 does not exist in the array, so accessing its value will return the special value undefined . Use the length attribute to easily add elements to the end of the array, as shown in the following example:

let colors = ['red', 'blue', 'green'] // 创建一个包含 3 个字符串的数组

colors[colors.length] = 'black' // 添加一种颜色(位置3)

colors[colors.length] = 'brown' // 再添加一种颜色(位置4)

The index of the last element in the array is always length - 1 , so the index of the next new slot is length . Every time an item is added after the last element of the array, the length attribute of the array will be automatically updated to reflect the change. This means that the second line colors[colors.length] will be in a position 3 add a new element, the next line will be in a position 4 add a new element. The new length is automatically updated when a new element is added to a position outside the current array. In other words, the length attribute will be updated to the position plus 1 , as shown in the following example:

let colors = ['red', 'blue', 'green'] // 创建一个包含 3 个字符串的数组

colors[99] = 'black' //添加一种颜色(位置99)

console.log(colors.length) // 100

Here, colors array is inserted at position 99 , and as a result, the new length becomes 100(99 + 1) . All the elements in the middle, that is, position 3~98 , do not actually exist, so undefined will be returned when accessed.

Common methods of arrays

1.Array.join()

join() method is used to put all the elements in the array into a string. join() method can pass in a separator, and the elements are separated by the separator. If the separator is not passed, it will be separated by a comma by default.

let Array = ['apple', 'banner', 'cat']

let joinArray1 = Array.join(' ')
console.log(joinArray1) // 'apple banner cat'

let joinArray2 = Array.join('-')
console.log(joinArray2) // 'apple-banner-cat'

let joinArray3 = Array.join()
console.log(joinArray3) // 'apple,banner,cat'

2.Array.pop()

pop() method is used to delete and return the last element of the array. pop() method removes arrayObject last element, the array length minus 1 , and returns the value of its elements removed. If the array is already empty, pop() does not change the array and returns the value undefined

let Array = ['apple', 'banner', 'cat']

let popArray = Array.pop()
console.log(popArray) // 'cat'
console.log(Array) //[ 'apple', 'banner' ]

3.Array.push()

push() method adds one or more elements to the end of the array and returns the new length. push() method can add its parameter sequence to the end of arrayObject It directly modifies arrayObject instead of creating a new array. push() method and the pop() method use the first-in-last-stack function provided by the array.

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' ]

4.Array.reverse()

reverse() method is used to reverse the order of the elements in the array. And this method will change the original array, but will not create a new array. The return value of this function is a pointer to the original 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

5.Array.shift()

shift() method is used to delete the first element of the array and return the value of the first element. If the array is empty, then the shift() method will do nothing and return the undefined value. This method does not create a new array, but directly modifies the original arrayObject .

let Array = ['apple', 'banner', 'cat']

let shiftArray = Array.shift()
console.log(shiftArray) // 'apple'
console.log(Array) // [ 'banner', 'cat' ]

6.Array.unshift()

unshift() method adds one or more elements to the beginning of the array and returns the new length. unshift() method will insert its parameters into arrayObject , and sequentially move the existing elements to higher subscripts to make room. The first parameter of this method will become the new element 0 of the array, if there is a second parameter, it will become 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' ]

7.Array.slice()

slice() method can return selected elements from an existing array. Return a new array containing arrayObject start to end (not including this element). You can use negative values to select elements from the end of the array. If end is not specified, then the slice() method will select 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' ]

8.Array.splice()

splice() method modifies the array by deleting or replacing existing elements or adding new elements in place, and returns the modified content in the form of an array. This method will change the original array. splice() method can delete index , and replace those deleted elements with one or more values declared in the parameter list. If arrayObject , it returns an array containing the deleted element.

let Array = ['apple', 'banner', 'cat']

// 只填第一和第二个参数是删除数组中元素并返回删除的元素数组
let spliceArray1 = Array.splice(1, 1)
console.log(spliceArray1) // [ 'banner' ]
console.log(Array) // [ 'apple', 'cat' ]

// 如果第二个参数写为0则不会删除
let spliceArray2 = Array.splice(1, 0)
console.log(spliceArray2) // []
console.log(Array) // [ 'apple', 'cat' ]

// 如果除了两个参数外还有别的参数,会在删除完后在规定的起始位置添加元素
let spliceArray3 = Array.splice(1, 1, 'hello', 'xhs')
console.log(spliceArray3) // [ 'cat' ]
console.log(Array) // [ 'apple', 'hello', 'xhs' ]

Array traversal

There are many ways to traverse the array, the following shows a few of the more common traversal methods

1. 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

2. for...in...

for...in... will traverse the index value of all the data in the array, and then obtain the value corresponding to each index through the index value.

let array = [1, 2, 3, 4, 5]
for (let i in array) {
  console.log(array[i])
}
// 1
// 2
// 3
// 4
// 5

3. forEach()

Each array has a forEach . The parameter of this function is a callback function. Each time the value in the array is passed in, the callback function is called once until the traversal is completed.

let array = [1, 2, 3, 4, 5]
array.forEach(function (item) {
  console.log(item)
})
// 1
// 2
// 3
// 4
// 5

Self-test

One: What does the following code output

const numbers = [1, 2, 3]
numbers[10] = 11
console.log(numbers)
  • A: [1, 2, 3, 7 x null, 11]
  • B: [1, 2, 3, 11]
  • C: [1, 2, 3, 7 x empty, 11]
  • D: SyntaxError

2: 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)
  • A:1238
  • B:14
  • C:9
  • D:123NaN

3: What will be output when the following code is executed

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)
  • A: 15
  • B: 16
  • C: 19
  • D: 012565

Problem analysis

One,
Answer: C

js can be dynamically increased. numbers[10]=11 makes the length of the array become 11 , and only 0、1、2、10 has a value, the middle element is empty, printed in the array as empty , and when accessed as an element, it is undefined .


two,
Answer: D

Original array have 5 elements, length 5 , by modifying lenth property, after deleting the two elements, this time array=[1,2,3] , when accessing array[3] , the resulting undefined , undefined*2 give NaN , so array case becomes [1,2,3,NaN] . num initialized as a string, so the traversal is to concatenate all the elements with strings, and finally output 123NaN


three,
Answer: C

Because array2=array1 , using array1 and array2 point to the same array, after modification, the array becomes [1,2,5,6,5] , after accumulation, the answer is 19


小和山的菜鸟们
377 声望2.1k 粉丝

每日进步的菜鸟,分享前端学习手册,和有心学习前端技术的小伙伴们互相探讨,一同成长。