Strictly speaking, an array data type does not exist in JavaScript, but JavaScript does provide an object with array properties

With some encapsulation and a set of syntactic sugar, this object is as easy to use as a real array

Create an array

(1) Array literal

Array literals consist of zero or more comma-delimited expressions, each of which can be of any type, and all of which are enclosed in square brackets

> // Create an empty array
> var empty = []
> // Create an array with contents
> var fruit = ['apple'.'banana'.'cherry']
Copy the code

Examine the array you just created and find that it is of type Object

> typeof fruit
// 'object'
Copy the code

When you create an array, each element in the array gets a default attribute name, the first being ‘0’, the second being ‘1’, and so on

Finally, attribute names and element values are stored as key-value pairs, similar to an object created directly from object direct quantities below

> var fruit = {'0': 'apple'.'1': 'banana'.'2': 'cherry'}
Copy the code

Of course, there are a number of differences between creating arrays using array quantities and creating objects using object quantities

  • Arrays inherit fromArray.prototypeObject inherits fromObject.prototypeThe two have different methods
  • Arrays have a magic length property that objects do not

(2) New Array()

You can create an Array using the new operator plus the Array constructor

> // Create an empty array
> var empty = new Array(a)Copy the code

2. Add, delete, change and check elements

0) The index of the array

For a regular array, the index of an array is a positive integer incremented from zero, but in JavaScript the situation is different

Since an array is a type of object, we can theoretically index an array using any legal string, just as we index object properties

So how do you distinguish array indexes from object properties?

JavaScript states that only integers between [0, 2**32) can be used as array indexes, otherwise they can only be treated as object attributes

(1) Element reading (lookup)

Elements in an array are accessed using the square bracket operator ([])

To the left of the square brackets is a reference to the array, and inside the square brackets is an arbitrary expression that returns a non-negative integer as the index of the array

> var fruit = ['apple'.'banana'.'cherry']
> fruit[0]
// 'apple'
Copy the code

Remember, arrays are a special form of objects, so using square brackets to access array elements is just like using square brackets to access object properties

JavaScript converts a numeric index value to a string index value, which is then used as an attribute name

(2) Element setting (modification)

You can also set the value of an element using the square bracket operator

> var fruit = ['apple'.'banana'.'cherry']
> fruit[0] = 'almond'
> fruit[0]
// 'almond'
Copy the code

(3) Element deletion (delete)

  • Delete operator: Sets the element value of the specified index to undefined in the original array
> var drink = ['milk'.'tea'.'coffee']
> delete drink[1]
> drink[1]
// undefined
> drink[2]
// coffee
Copy the code
  • The pop method deletes the last element in the original array and returns the deleted element
> var drink = ['milk'.'tea'.'coffee'.'beer']
> var drink_popped = drink.pop()
> drink
// ['milk', 'tea', 'coffee']
> drink_popped
// 'beer'
Copy the code
  • Shift removes the first element in the array and returns the deleted element
> var drink = ['milk'.'tea'.'coffee'.'beer']
> var drink_shifted = drink.shift()
> drink
// ['tea', 'coffee', 'beer']
> drink_shifted
// 'milk'
Copy the code
  • The splice method deletes a specified element from the array. The first argument specifies the starting index and the second argument specifies the length
> var drink = ['milk'.'tea'.'coffee'.'coke'.'sprite'.'beer']
> var drink_spliced = drink.splice(3.2)
> drink
// ['milk', 'tea', 'coffee', 'beer']
> drink_spliced
// ['coke', 'sprite']
Copy the code

(4) Increase of elements (increase)

  • The easiest way to add elements is to assign a value to a new index
> var food = ['rice'.'meat'.'vegetable']
> food[3] = 'noodle'
> food
// ['rice', 'meat', 'vegetable', 'noodle']
Copy the code
  • Push: adds an element to the end of the array and returns the number of elements in the new array
> var food = ['rice'.'meat'.'vegetable']
> var food_length = food.push('bread')
> food
// ['rice', 'meat', 'vegetable', 'bread']
> food_length
/ / 4
Copy the code
  • Unshift: Adds an element to the top of the array. Returns the number of elements in the new array
> var food = ['rice'.'meat'.'vegetable']
> var food_length = food.unshift('bread')
> food
// ['bread', 'rice', 'meat', 'vegetable']
> food_length
/ / 4
Copy the code
  • Splice method: In addition to deleting elements from an array, the splice method can also add elements with a third optional argument
> var food = ['rice'.'meat'.'vegetable']
> var food_spliced = food.splice(2.0.'fish')
> food
// ['rice', 'meat', 'fish', 'vegetable']
> food_spliced
/ / []
Copy the code

3. Traversal of elements

Since arrays are also objects, we can iterate over arrays in the same way we iterate over objects, with for-in and for-of loops commonly used

> var fruit = ['apple'.'banana'.'cherry']
> fruit[5] = 'filbert'
> / / the for - in circulation
> for (let index in fruit) {
    console.log(fruit[index])
}
// apple
// banana
// cherry
// filbert
> / / the for - cycle
> for (let item of fruit) {
    console.log(item)
}
// apple
// banana
// cherry
// undefined
// undefined
// filbert
Copy the code

The length property of the array

The value of the JavaScript array length property is not necessarily equal to the number of elements in the array; it is actually equal to the largest legal index in the array plus 1

One rule here is that you can never find an element in an array whose index value is greater than or equal to its length

To maintain this rule, the length attribute has a number of interesting behaviors

  • If you assign a value to an array element and its index I is greater than or equal to the existing array length, the length property is set to I + 1
> var alphabet = ['a'.'b'.'c']
> alphabet.length
/ / 3
> alphabet[4] = 'e'
> alphabet.length
/ / 5
Copy the code
  • If you assign a value to an array element whose index is not a valid array index, the value of the length attribute will not change
> var alphabet = ['a'.'b'.'c']
> alphabet.length
/ / 3
> alphabet[-1] = 'z'
> alphabet.length
/ / 3
Copy the code
  • When the length attribute is set to a non-negative integer n less than the current length, elements whose index value is greater than or equal to n are deleted
> var alphabet = ['a'.'b'.'c']
> alphabet.length
/ / 3
> alphabet.length = 1
> alphabet
// ['a']
Copy the code

5. Array methods

JavaScript provides a set of methods for arrays, which are functions stored in array.prototype

(1) Regular array methods

  • Join: Converts all elements in an array to a string and concatenates them together, returning the concatenated string

    You can specify a delimiter with an optional argument (of type string), using a comma by default

> var numbers = [0.1.2.3.4.5.6.7.8.9]
> var numbers_join = numbers.join()
> numbers_join
/ / '0,1,2,3,4,5,6,7,8,9'
Copy the code
  • Reverse: Sorts the elements in an array in reverse order and returns the sorted array
> var numbers = [0.1.2.3.4.5.6.7.8.9]
> var numbers_reverse = numbers.reverse()
> numbers_reverse
// [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Copy the code
  • Sort: Sort the elements of an array according to certain rules and return the sorted array

    Comparison rules between elements can be specified with an optional argument (function type), which defaults to lexicographical order

> var numbers = [111.3.22]
> ns1 = numbers.sort() // To a string, in lexicographical order
> ns2 = numbers.sort(function(a, b) { return a < b }) // Arrange in ascending order
> ns3 = numbers.sort(function(a, b) { return a > b }) // Order them in ascending order
> ns1
// [111, 22, 3]
> ns2
// [111, 22, 3]
> ns3
// [3, 22, 111]
Copy the code
  • Concat: Concatenates the elements of two arrays, returning the concatenated array
> var a = [1.2.3]
> var b = [4.5[7], [8.9]]
> var c = a.concat(b)
> var d = b.concat(a)
> c
// [1, 2, 3, 4, 5, [7], [8, 9]]
> d
// [4, 5, [7], [8, 9], 1, 2, 3]
Copy the code
  • Slice: Returns an array fragment of a specified range

    If you omit the second argument, it defaults to the end of the array. If you omit the first argument, it defaults to the beginning of the array

> var a = [1.2.3.4.5]
> var b = a.slice(1.4)
> var c = a.slice(2) // Omit the second argument
> var d = a.slice() // Omit both the second and first arguments
> b
// [2, 3, 4]
> c
// [3, 4, 5]
> d
// [1, 2, 3, 4, 5]
Copy the code
  • Includes: Checks whether the array contains a specific element, returning true if it does, false if it does not
> var numbers = [1.2.3.4.5]
> numbers.includes(0)
// false
> numbers.includes(1)
// true
Copy the code
  • IndexOf: Checks whether the array contains a specific element, returns the index if it does, and -1 if it does not
> var numbers = [1.2.3.4.5]
> numbers.indexOf(0)
// -1
> numbers.indexOf(1)
/ / 0
Copy the code

(2) ECMAScript5 array methods

ECMAScript5’s newly defined array methods have some similar features, which are described here

Most of these methods take a function as an argument and call that function once for each element in the array

This function takes three arguments, an array element, an element index, and the array itself

  • forEach
> var numbers = [1.3.5.7.9]
> // Evaluates the sum of all elements in the array
> var sum = 0
> numbers.forEach(function(value){
    sum += value
})
> sum
/ / 25
> // Increments each element in the array by 1
> numbers.forEach(function(value, index, array){
    array[index] = value + 1
})
> numbers
// [2, 4, 6, 8, 10]
Copy the code
  • map
> var numbers = [1.2.3.4.5]
> // Multiply each element in the array by 2 and return a new array
> var numbers_doubled = numbers.map(function(number){
    return (number * 2)
})
> numbers_doubled
// [2, 4, 6, 8, 10]
Copy the code
  • filter
> var numbers = [1.2.3.4.5.6.7.8.9.10]
> // Leave an even number of elements
> var even_numbers = numbers.filter(function(number){
    return (number % 2= = =0)
})
> even_numbers
// [2, 4, 6, 8, 10]
Copy the code
  • every / some
> function isPrime(val) {
    if (val < 2) {
        return false
    } else if (val === 2) {
        return true
    } else { // val > 2
        if (val % 2= = =0) {
            return false
        } else { // val % 2 ! = = 0
            for (let i = 3; i * i <= val; i += 2) {
                if (val % i === 0) {
                    return false}}return true}}} >// Check whether each element in the array is prime
> [2.3.5.7].every(function(value){
    return isPrime(value)
})
// true
> [2.3.5.7.9].every(function(value){
    return isPrime(value)
})
// false
> // Check whether there is an element in the array that is prime
> [4.6.8.9].some(function(value){
    return isPrime(value)
})
// false
> [2.4.6.8.9].some(function(value){
    return isPrime(value)
})
// true
Copy the code

Here to give you a problem, please write the following program execution results

['1'.'3'.'10'].map(parseInt)
Copy the code

The output is [1, NaN, 2]. Is that correct

There are two key points to solve this problem, one is the principle of map function, the other is the principle of parseInt function

\

The map function applies the function specified in the parameter to each element of an array and returns the result as an array

It takes the current element of the array as the first argument, the index of that element as the second argument, and the array itself as the third argument

ParseInt (‘1’, 0), parseInt(‘3′, 1), parseInt(’10’, 2)]

\

Ok, now let’s look at the parseInt function, which essentially converts a string to a decimal number

The first argument it takes is the string to be parsed, and the second argument indicates the cardinality to use, which can be 0 or between 2 and 36

ParseInt (‘ 1 ‘, 0) : base is 0, the default decimally parsing string, () function converts a decimal number 1 to a decimal number is 1

ParseInt (‘3’, 1) : The cardinality is neither 0 nor between 2 and 36, so NaN is returned

ParseInt (’10’, 2) : The base is 2, so the string is parsed in binary, converting the binary number 10 to the decimal number 2

So the end result is [1, NaN, 2]