Array creation

Arrays can be created in three ways: constructors, literals, and array.of ().

Constructor mode

let arr = new Array(); // create an empty Array let arr = new Array(10); // create an empty Array of length 10 let arr = new Array('a'); Let arr = new Array(10,'a'); // Create an array containing 10 and the string aCopy the code

Summary:

1. The new keyword can be omitted

2. When only one number element is passed, an array of the specified length is created. The constructor cannot create an array containing only one number element.

Literal way:

let arr = [10,'a']; // Literal, that is, assigning values to arrays directlyCopy the code

Array.of() method (new in ES6) :

The () method converts a set of values (parameters passed in) to an array.

This method compensates for the constructor’s inability to create an array with only one element of type number

Let arr = array. of(3); The console. The log (arr); / / [3]Copy the code

Parameters can be of various types

let arr1 = Array.of(1,'a',true,null,undefined,{name:"zhangsan"},[45]);
console.log(arr1);  // [1,'a',true,null,undefined,{name:"zhangsan"},[45]];
Copy the code

Array detection:

Two more accurate detection methods:

1. Use the object’s toString method

Object.prototype.toString().call([]) === "[object Array]"; // true Array.isArray(); Array. IsArray ([1, 2, 3]); // trueCopy the code

Array properties:

Length attribute:

Sets or returns the length of the array.

Can be used to add and remove array items;

Let arr = [1, 2]; arr.length = 1; console.log(arr); // [1] arr.length = 3; console.log(arr); / / / 1,,Copy the code

Array methods

JavaScript array methods include array prototype methods, constructor methods (new in ES6);

There are four main things we know about each method: what it does, its parameters, its return value, and whether the array changes.

(I). The method on the prototype

1, push () :

Adds one or more items to the end of an array.

Parameters: ele1 [, ele2 [, elen], […]]

Return value: The length of the array after the element is added

Whether the original array is changed: Yes

Let arr = [1, 2, 3]; let temp = arr.push('a','b'); console.log(arr,temp); / / [1, 2, 3, 'a', 'b'] 5Copy the code

2,  pop():

Delete the last item of the array,

Parameters: no

Return value: the deleted item,

Whether the original array is changed: Yes

Let arr = [1, 2, 3]; let temp = arr.pop(); console.log(arr,temp); 3 / / [1, 2]Copy the code

3,  unshift():

Adds one or more items to the beginning of an array.

Parameters: ele1 [, ele2 [, elen], […]]

Return value: The length of the array after the element is added

Whether the original array is changed: Yes

Let arr = [1, 2, 3]; let temp = arr.unshift('a','b'); console.log(arr,temp); / / / 'a', 'b', 1, 2, 3] 5Copy the code

4,shift():

Deletes the first item of an array.

Parameters: no

Return value: the deleted item;

Whether the original array is changed: Yes

(loading)