1. Array declaration

(1) Create array

Create arrays using objects

new Array(1.'huihui');
Copy the code

Create arrays using literals

const array = [1.'huihui];
Copy the code

An array is a reference type that can be declared and its value modified using const

const array = [1.'huihui'];
array.push('cute');
Copy the code

Use the length attribute of the stereotype to get the number of array elements

const array = [1.'huihui'];
console.log(array.length)
Copy the code

Arrays can be set to any value. Here’s how to add an array using an index

let arr = ['huihui'];
arr[1] = 18;
Copy the code

The next step is to set the array number 3 directly, which will define the 1/2 indexed array as undefined

let arr = ['huihui'];
arr[3] = 19;
console.log(a[1])    // undefined
console.log(a[2])    // undefined
Copy the code

Declares an array of empty elements

let arr = new Array(3);
console.log(arr.length)    / / 3
console.log(arr)    / / / the empty x 3
Copy the code

(2) the Array of

Unlike new Array, using array. of does not create an Array of empty elements when setting a parameter

let arr = Array.of(3);
console.log(arr)    / / [3]

arr = Array.of(1.2.3);
console.log(arr);    / / [1, 2, 3]
Copy the code

(3) Type detection

console.log(Array.isArray(['huihui'.18]));    // true
console.log(Array.isArray(9))    // false
Copy the code

2. Type conversion

You can convert an array to a string or any other type to an array

(1) String

Use.toString() to convert an array to a character transform

console.log(([1.2.3]).toString());    / / 1, 2, 3
Copy the code

Use the function String to convert to a String

console.log(String([1, 2, 3]))
Copy the code

Join strings using join

consoe.log([1.2.3].join(The '-'))    / / 1-2-3
Copy the code

(2) Array. The from

Use array. from to convert a class Array to an Array. A class Array is an object that contains a length attribute or is iterable

let str = 'Zhang Xiaohui';
console.log(Array.from(str))    // [" zhang ", "xiao "," Hui "]
Copy the code

An object can also be converted to an array by setting the length property, but with a numeric subscript or numeric string

let str = {
  0: 'zxh'.'1': 18.length: 2
};
console.log(Array.from(str)); //["zxh", 18]
Copy the code

3. Expand the grammar

(1) Array merge

It’s easier to merge arrays using an expansion than concat, using… You can expand an array into multiple values

let a = [1.2.3];
let b = ['a'. a];console.log(b)    // ['a', 1, 2, 3]
Copy the code

(2) Function parameters

Use expansion syntax instead of arguments to accept any number of arguments.

let hd(. args){
    console.log(args);
}
hd(1.2.3);    / / [1, 2, 3]
Copy the code

Using the expansion syntax can also be used to accept partial parameters

let hd(name, ... args){
    console.log(args);
}
hd("huihui".1.2.3);    / / [1, 2, 3]
Copy the code

4. Deconstruct assignments

Deconstruction is a simpler assignment property that can be understood as breaking up the structure of a piece of data

(1) Basic use

let [name, age] = ['huihui'.19];
console.log(name, age)    // huihui 19
Copy the code

Structure assignment array

function test() {
    return ['huihui'.19]}let [name, age] = test();
console.log(name, age)    // huihui 19
Copy the code

Residual deconstruction is the use of a variable to receive residual parameters

let [a, ...b] = ['test'.1.2.3.4];
console.log(b)    // [1, 2, 3, 4]
Copy the code

String deconstruction

const [...test] = 'zhangxiaohui';
console.log(test);    // ["z", "h", "a", "n", "g", "x", "i", "a", "o", "h", "u", "i"]
Copy the code

(2) Concise definition

Only some variables are assigned

let [, age] = ['huihui'.18];
console.log(age)    / / 18
Copy the code

Get multiple values using expansion syntax

let [name, ...arr] = ['huihui'.1.2.3.4.5];
console.log(name);    // huihui
console.log(arr);    // [1, 2, 3, 4, 5]
Copy the code

(3) Default value

Set default values for variables

let [name, age = 18] = ['huihui'];
console.log(age);    / / 18
Copy the code

(4) Function parameters

Use of function arguments

function test([a, b]) {
    console.log(a, b)
}
test(['huihui'.18])
Copy the code

5. Management elements

(1) Basic use

push

Changes the array directly by pressing in the element, returning the number of array elements

let test = [1];
test.push(2);
console.log(test)    / / [1, 2]
Copy the code
let test = [{name: 'huihui'}];
test.push({name: 'dudu'});
console.log(test);    // [{name: 'huihui'}, {name: 'dudu'}]
Copy the code
pop

Eject the element from the end, changing the array directly, and returning the ejected element

let test = [1.2];
console.log(test.pop())    / / 2
Copy the code
let test = [{name: 'huihui'}]; 
console.log(test.pop());    // ['huihui']
Copy the code
shift

Retrieves an element from the front of the array

let test = ['huihui'.19];
console.log(test.shift())    // 'huihui'
Copy the code
let test = [{name: 'huihui'}]; 
console.log(test.shift());    // {name: "huihui"}
Copy the code
unshift

Adds elements from the front of the array

let test = [2.3];
console.log(test.unshift(0.1))    / / 4
console.log(test)    // [0, 1, 2, 3]
Copy the code
let test = [{name: 'huihui'}];
test.unshift({name: 'dudu'});
console.log(test);    //[{name: "dudu"}, {name: "huihui"}]
Copy the code
fill

Fill elements with the Fill array

console.dir(Array(4).fill("huihui")); //["huihui", "huihui", "huihui", "huihui"]
Copy the code

Specify fill location

console.log([1.2.3.4].fill("huihui".1.2)); //[1, "huihui", 3, 4]
Copy the code
slice

Slice is used to slice a portion of an array. This method is used to slice a portion of an array.

Arr. slice(start, end) // Indicates that the slice starts from the start position and ends from end-1

let arr = [0.1.2.3.4.5.6];
console.log(arr.slice(1.3)); / / [1, 2]
Copy the code

Get all elements without setting parameters

let arr = [0.1.2.3.4.5.6];
console.log(arr.slice()); //[0, 1, 2, 3, 4, 5, 6]
Copy the code
splice

The splice method adds, removes, and replaces elements in an array, changing the array and returning the number of deleted elements

The first parameter to delete an array element is where to start, the second parameter is the number of elements to delete, and the third parameter is the element added at the deleted location

delete

let arr = [0.1.2.3.4.5.6];
console.log(arr.splice(1.3)); // Return the deleted element [1, 2, 3]
console.log(arr); // Delete data from array [0, 4, 5, 6]
Copy the code

Add/Replace

let arr = [0.1.2.3.4.5.6];
console.log(arr.splice(1.3.'huihui'.'the')); / / [1, 2, 3]
console.log(arr); //[0, "huihui", "19", 4, 5, 6]
Copy the code

(2) Merger and split

join

Join to a string using join

let arr = ['huihui'.19];
console.log(arr.join(The '-'))    // "huihui-19"
Copy the code
split

The split method is used to split a string into an array, similar to the inverse of the join method

let str = 'huihui-19';
console.log(str.split("-"))    // ["huihui", "19"]
Copy the code
concat

The concat method is used to concatenate two or more arrays, copy elements that are value types, and reference types that refer to the same object

let array = ["huihui".18];
let array1 = [1.2];
let array2 = [3.4];
console.log(array.concat(array1, array2));    // ["huihui", 18, 1, 2, 3, 4]=
Copy the code

You can also use extended syntax to implement joins

console.log([...array, ...array1, ...array2])
Copy the code
copyWithin

Use copyWithin to copy a portion of the array to another location in the same array

(3) Find elements

indexOf

Use indexOf to find the location of the element from front to back, returning -1 if it cannot be found

let arr = [7.3.2.8.2.6];
console.log(arr.indexOf(2)); // 2 looks for the position where 2 appears
Copy the code

Note: indexOf is strictly type constrained

let arr = [7.3.2.'8'.2.6];
console.log(arr.indexOf(8)); // -1
Copy the code

The second parameter specifies where the search starts

let arr = [7.3.2.8.2.6];
// Start with the second element and look backwards
console.log(arr.indexOf(2.3)); / / 4
Copy the code
lastIndexOf

Find the element from back to front, and return -1 if you cannot find it

let arr = [7.3.2.8.2.6];
console.log(arr.lastIndexOf(2)); // 4 looks for the position where 2 appears
Copy the code

The second parameter specifies where to look

let arr = [7.3.2.8.2.6];
// Look forward from the fifth element
console.log(arr.lastIndexOf(2.5));

// Look forward from the last character
console.log(arr.lastIndexOf(2, -2));
Copy the code
includes

Using includes to find the string returns a Boolean value

let arr = [7.3.2.6];
console.log(arr.includes(6)); //true
Copy the code

The implementation principle of includes functions

function includes(array, item) {
  for (const value of array)
    if (item === value) return true;
    // Notice that the for loop is broken and returns false
  return false;
}

console.log(includes([1.2.3.4].3)); //true
Copy the code
find

The find method returns the value if not found. Note: Returns the value of the first lookup and does not continue the lookup.

let arr = ["huihui"."eva"."luna"];

let find = arr.find(function(item) {
  return item == "huihui";
});

console.log(find); //huihui
Copy the code

Reference types cannot be found with includes because their memory addresses are not equal.

const user = [{ name: "Bill" }, { name: "Zhang" }, { name: "huihui" }];
const find = user.includes({ name: "huihui" });
console.log(find);
Copy the code

Find makes it easy to find reference types

const user = [{ name: "Bill" }, { name: "Zhang" }, { name: "huihui" }];
const find = user.find(user= > (user.name = "huihui"));
console.log(find);
Copy the code
findIndex

The difference between findIndex and find is that it returns the index value, or -1 if it cannot be found

let arr = [7.3.2.'8'.2.6];

console.log(arr.findIndex(function (v) {
	return v == 8;
})); / / 3
Copy the code
Find the principle
let arr = [1.2.3.4.5];
function find(array, callback) {
  console.log('callback', callback)
  for(const value of array) {
    if(callback(value) === true) return value
  }
  return undefined
}
let res = find(arr, function(item) {
  return item == 5
});
console.log(res)
Copy the code

(4) Array sort

reverse
let arr = [1.4.2.9];
console.log(arr.reverse()); / / [9, 2, 4, 1)
Copy the code
sort

Sort from largest to smallest using the sorting function, comparing argument one with argument two, and returning positive as descending and negative as ascending

let arr = [1.4.2.9];

console.log(arr.sort(function (v1, v2) {
	return v2 - v1;
})); / / [9, 4, 2, 1]
Copy the code
Principle of sorting

Quick sort

(5) Loop traversal

for
forEach

ForEach causes the function to operate on each element of the array, but forEach cannot return without returning a value

for/in

The traversal key is the index of the array

let lessons = [
  {title: 'Media Query Responsive Layout'.category: 'css'},
  {title: 'FLEX Box model '.category: 'css'},
  {title: MYSQL > select * from 'select * from' where '.category: 'mysql'}];for (const key in lessons) {
    console.log(key);
}    / / 0 1 2
Copy the code
for/of

Unlike for/in, for/of takes the value of each loop instead of the index

let lessons = [
  {title: 'Media Query Responsive Layout'.category: 'css'},
  {title: 'FLEX Box model '.category: 'css'},
  {title: MYSQL > select * from 'select * from' where '.category: 'mysql'}];for (const item of lessons) {
  console.log(item)
}
// The output is:
{title: "Media Query Responsive Layout".category: "css"}
{title: "FLEX Elastic box Model".category: "css"}
{title: MYSQL > alter table select * from 'MYSQL';.category: "mysql"}

Copy the code

(6) Iterator method

keys
let lessons = [
  {title: 'Media Query Responsive Layout'.category: 'css'},
  {title: 'FLEX Box model '.category: 'css'},
  {title: MYSQL > select * from 'select * from' where '.category: 'mysql'}];console.log(lessons.keys())    // Array Iterator {} Why? Why is that?
Copy the code
const array = ["huihui"."eva"];
const keys = array.keys();    // Array Iterator {}
console.log(keys.next());    // {value: 0, done: false}
console.log(keys.next());    // {value: 1, done: false}   
console.log(keys.next());    // {value: undefined, done: true} 

for(const key of array.keys()) {
    console.log(key)    / / 0 to 1
}
Copy the code
values
const array = ["huihui"."eva"];
const keys = array.values();    // Array Iterator {}
console.log(keys.next());    // {value: 0, done: false}
console.log(keys.next());    // {value: 1, done: false}    
console.log(keys.next());    // {value: undefined, done: true}  

for(const key of array.values()) {
    console.log(key)    // 'huihui' 'eva'
}
Copy the code
entries

Returns all key-value pairs of an array

const arr = ["a"."b"."c",];
for (const [key, value] of arr.entries()) {
  console.log(key, value);
}
// The output content is
0 "a"
1 "b"
2 "c"
Copy the code

(7) Extended methods

every

Every is used to recursively check elements and is true only if all element operations return true. The first argument is an element, the second argument is an index, and the third argument is an array.

some

The some function is used to recursively check for elements, and if one of them returns true, the expression is true. The first argument is an element, the second argument is an index, and the third argument is an array.

filter

Filter Can filter elements in data.

map

A map map applies functions to all elements of an array to map new values

reduce
arr.reduce(callback, [initialValue])
Copy the code

Callback executes a function for each value in the array and contains four arguments

  1. Pre: The value returned from the last call, or the initial value provided
  2. Cur: The element currently being processed in the array
  3. Index: Index of the current element in the array
  4. Array: array for invoking Reduce
let arr = [1.2.3.4];
let sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
})
console.log(arr, sum);

// The output is
1 2 1
3 3 3 2
3 6 4 3
[1.2.3.4] 10
Copy the code

The array is 4 in length, but the reduce function loops three times. Because index starts at 1

let arr = [1.2.3.4];
let sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    returnprev + cur; },0)
console.log(arr, sum);

// The output is
0 1 0
1 2 1
3 3 2
6 4 3
(4) [1.2.3.4] 10
Copy the code

The array length is 4, and the reduce function loops four times. Because I set pre to zero

(1) Count the number of occurrences of each element in the array

names = ['alice'.'bob'.'tiff'.'alice']
let nameNum = names.reduce((pre, cur) = > {
        console.log(The value of 'pre 'is:, pre)
        console.log('cur 'has the value:, cur)
        if(cur in pre) {
                pre[cur]++
        } else {
                pre[cur] = 1
        }
        console.log(pre)
        return pre
}, {})
console.log(nameNum)    // {alice: 2, bob: 1, tiff: 1}
Copy the code

(2) Array deduplication

let arr = [1.2.3.4.4.1];
let newArr = arr.reduce((pre, cur) = > {
        if(! pre.includes(cur)){return pre.concat(cur)
        } else {
                return pre
        }
},[])
console.log(newArr)    // [1, 2, 3, 4]
Copy the code

(3) Convert a two-dimensional array into a one-dimensional array

let arr = [[0.1], [2.3], [4.5]].let concatArr = arr.reduce((pre, cur) = > {
        return pre.concat(cur)
},[])
console.log(concatArr)    // [0, 1, 2, 3, 4, 5]
Copy the code

(4) Object attribute summation

let result = [
    {
        subject: 'math'.score: 10
    },
    {
        subject: 'chinese'.score: 20
    },
    {
        subject: 'english'.score: 30}];let total = result.reduce((pre, cur) = > {
        return pre + cur.score
}, 0)
console.log(total)    / / 60
Copy the code

(8) Array application

(1) Several ways to empty the array
(2) Several methods of array deduplication

—- to be continued