JavaScript study notes (3) array

JavaScript study notes (3) array

Strictly speaking, the data type of array does not exist in JavaScript, but JavaScript provides an object with array characteristics

And through a certain encapsulation, and provide a series of syntactic sugar, make this object as convenient as a real array

1. Create an array

(1) Array literal

The array literal consists of zero or more expressions separated by commas. The value of each expression can be of any type. All expressions are enclosed in square brackets.

> //Create an empty array > var empty = [] > //create an array with a content of > var Fruit = [ 'Apple' , 'Banana' , 'Cherry' ] duplicated code

Check the array just created and found that it is an object type

> Typeof Fruit //'Object' duplicated code

When creating an array, each element in the array will get a default attribute name, the first one is

'0'
, The second is
'1'
, And so on

Finally, the attribute name and element value are stored in the form of key-value pairs, similar to an object created directly with the object directly below

> Var Fruit = { '0' : 'Apple' , '. 1' : 'Banana' , '2' : 'Cherry' } copy the code

Of course, there are still many differences between the two (using an array to create an array and using an object to create an object)

  • Array inherited from
    Array.prototype
    , The object inherits from
    Object.prototype
    , The methods of the two are different
  • The array has a magic length property, but the object does not

(2)

new Array()

You can use the new operator plus the Array constructor to create an array

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

2. Add, delete, modify and check elements

(0) Index of the array

For regular arrays, the index of the array is a positive integer that starts from zero and increases continuously, but the situation is different in JavaScript

Because an array is also a kind of object, theoretically we can use any valid string to index an array, just like indexing object properties

So how to distinguish between array index and object property?

JavaScript stipulates that only

[0, 2**32)
The integer between can be used as an array index, otherwise it can only be used as an object property

(1) Reading of elements (check)

Use the square bracket operator (

[]
) Can access the elements in the array

The left side 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' duplicated code

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

JavaScript will convert the numeric index value into a string index value, and then use it as a property name

(2) Element settings (change)

The square bracket operator can also be used to set the value of an element

> var fruit = [ 'apple' , 'banana' , 'cherry' ] > Fruit [ 0 ] = 'Almond' > Fruit [ 0 ] //'Almond' duplicated code

(3) Deletion (deletion) of elements

  • delete operator: set the value of the element at the specified index in the original array to undefined
> var drink = [ 'milk' , 'tea' , 'coffee' ] > delete drink[ 1 ] > Drink [ . 1 ] //undefined > Drink [ 2 ] //Coffee duplicated code
  • pop method: delete the last element in the original array and return the deleted element
> var drink = [ 'milk' , 'tea' , 'coffee' , 'beer' ] > var drink_popped = drink.pop() > drink //['milk','tea','coffee'] > drink_popped //'beer' copy code
  • shift method: delete the first element in the original array and return the deleted element
> var drink = [ 'milk' , 'tea' , 'coffee' , 'beer' ] > var drink_shifted = drink.shift() > drink //['tea','coffee','beer'] > drink_shifted //'milk' copy code
  • splice method: delete the specified element in the original array, the first parameter specifies the starting index, the second parameter specifies the length, and returns the deleted element
> 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 the new index
> var food = [ 'rice' , 'meat' , 'vegetable' ] > food[ 3 ] = 'noodle' > food //[ 'rice', 'meat ', 'vegetable', 'noodle'] duplicated code
  • push method: add an element to the end of the original array and return 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 method: add an element to the front of the original array and return 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 in the array, the splice method can also add elements through the third optional parameter
> var food = [ 'rice' , 'meat' , 'vegetable' ] > var food_spliced = food.splice( 2 , 0 , 'fish' ) > food //['rice','meat','fish','vegetable'] > food_spliced //[] Copy code

3. Traversal of elements

Since the array is also a kind of object, we can traverse the array by traversing the object. Commonly used are for-in and for-of loops.

> var fruit = [ 'apple' , 'banana' , 'cherry' ] > fruit[ 5 ] = 'filbert' > //for-in loop > for ( let index in fruit) { console .log(fruit[index]) } //apple //banana //cherry //filbert > //for-of loop > for ( let item of fruit) { console .log(item) } The Apple// //Banana //Cherry //undefined //undefined //filbert copy the code

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

Here there is a rule that is in the array index of the element certainly can not find a value greater than or equal to its length

To maintain this rule, the length property has many interesting behaviors

  • If you assign a value to an array element and its index i is greater than or equal to the length of the existing array, the value of the length property will be 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 and its index is not a valid array index, the value of the length property will not change
> var alphabet = [ 'a' , 'b' , 'c' ] > alphabet.length //3 > alphabet[- 1 ] = 'z' > alphabet.length //3 copy the code
  • If the length property is set to a non-negative integer n less than the current length, those elements in the array whose index value is greater than or equal to n will be deleted
> var alphabet = [ 'a' , 'b' , 'c' ] > alphabet.length //3 > alphabet.length = 1 > alphabet //['a'] Copy code

5. Array method

JavaScript provides a set of methods to act on arrays, these methods are stored in

Array.prototype
The function

(1) Conventional array method

  • join: Convert all elements in the array into strings and splice them together, and return the spliced string

    You can specify the delimiter through an optional parameter (string type), and use 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' duplicated code
  • reverse: sort the elements in the array in reverse order and return 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 in the array according to certain rules and return the sorted array

    An optional parameter (function type) can be used to specify the comparison rule between elements, the default is dictionary order

> var numbers = [ 111 , 3 , 22 ] > ns1 = numbers.sort() //Converted to strings, arranged in lexicographic order > ns2 = numbers.sort( function ( a, b ) { return a <b }) //arranged in numerical order from largest to smallest > ns3 = numbers.sort( function ( a, b ) { return a> b }) //Sort by value from smallest to largest > ns1 //[111, 22, 3] > ns2 //[111, 22, 3] > ns3 //[3, 22, 111] copy the code
  • concat: concatenate the elements of two arrays and return 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]
  • slice

> var a = [1, 2, 3, 4, 5] > var b = a.slice(1, 4) > var c = a.slice(2) // > var d = a.slice() // > b //[ 2, 3, 4 ] > c //[ 3, 4, 5 ] > d //[ 1, 2, 3, 4, 5 ]
  • includes true false
> var numbers = [1, 2, 3, 4, 5] > numbers.includes(0) //false > numbers.includes(1) //true
  • indexOf -1
> var numbers = [1, 2, 3, 4, 5] > numbers.indexOf(0) //-1 > numbers.indexOf(1) //0

2 ECMAScript5

ECMAScript5

  • forEach
> var numbers = [1, 3, 5, 7, 9] > // > var sum = 0 > numbers.forEach(function(value){ sum += value }) > sum //25 > // 1 > numbers.forEach(function(value, index, array){ array[index] = value + 1 }) > numbers //[2, 4, 6, 8, 10]
  • map
> var numbers = [1, 2, 3, 4, 5] > // 2 > var numbers_doubled = numbers.map(function(number){ return (number * 2) }) > numbers_doubled //[2, 4, 6, 8, 10]
  • filter
> var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > // > var even_numbers = numbers.filter(function(number){ return (number % 2 === 0) }) > even_numbers //[2, 4, 6, 8, 10]
  • 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 } } } > // > [2, 3, 5, 7].every(function(value){ return isPrime(value) }) //true > [2, 3, 5, 7, 9].every(function(value){ return isPrime(value) }) //false > // > [4, 6, 8, 9].some(function(value){ return isPrime(value) }) //false > [2, 4, 6, 8, 9].some(function(value){ return isPrime(value) }) //true

['1', '3', '10'].map(parseInt)

[1, NaN, 2]
, Did you get it right

There are two key knowledge points to solve this problem, one is

map
The principle of the function, one is
parseInt
Principle of function

\

map
The principle of the function is to apply the function specified in the parameter to each element of the array, and then combine these results into an array to return

The first parameter it receives is the current element of the array, the second parameter is the index of the element, and the third parameter is the array itself

In fact, this program will return a result like this

[parseInt('1', 0), parseInt('3', 1), parseInt('10', 2)]

\

OK, let s take a look

parseInt
The role of the function, its role is actually to convert a string into a decimal number

The first parameter it receives is the parsed string, and the second parameter indicates the base to be used. This value can be 0 or between 2 and 36

parseInt('1', 0)
: The base is 0, and the string is parsed in decimal by default, and the decimal number is
1
Convert to decimal number or
1

parseInt('3', 1)
: The base is neither 0 nor in the range 2 ~ 36, so return
NaN

parseInt('10', 2)
: The base is 2, so the string is parsed in binary, and the binary number
10
The conversion to a decimal number is
2

So the final result is

[1, NaN, 2]