This is the 8th day of my participation in Gwen Challenge

Array deconstruction

Concepts in ES6 can be used in the form of a variable to extract the corresponding value syntax from an array according to certain rules (subscript matching patterns)

 // ES5
let arr = ['Guangdong'.'Guangzhou'.'xx road']
let province = arr[0]
let city = arr[1]
let street = arr[2]

// ES6 array structure
let [province, city, street] = ['Guangdong'.'Guangzhou'.'xx road']
// Variables with equal indices are matched with the same indices in the array
Copy the code

Pay attention to

  1. Array structures can have default values
let [, city, street] = ['Guangdong'.'Guangzhou'.'xx road']

console.log(city, street) // 'xx Road '
Copy the code
  1. The structure of the array allows for nested destructions
let [[f,b], ,arr] = [['foo'.'bar'].1[1.2.3]]

console.log(f, b, arr) / / 'foo' 'bar' [1, 2, 3]
Copy the code
  1. If not, undefined will be returned
let [, city, street, test] = ['Guangdong'.'Guangzhou'.'xx road']

console.log( test) // undefined
Copy the code
  1. Destruct supports default values
let [, city, street, test = The '42'] = ['Guangdong'.'Guangzhou'.'xx road']

console.log( test) / / no. 42
Copy the code

Object deconstruction

Concepts In ES6 objects can also extract corresponding values from objects according to certain rules (key matching pattern)

grammar

let {id, name, artist} = {
    id347230.name"Sea and sky".artist"Beyond".album"Sea and sky".duration326000.mark8192
}

console.log(id, name, artist) // 347230 "Beyond"
Copy the code

Pay attention to

  1. In the structure of an object, the order of variables does not affect the matched attributes. You must ensure that the variable name matches the object key

  2. The destructed variable name can be customized. The structure of the object is the key that the left structure object matches the data of the right object. Assign the value of the key on the right to the value variable on the left structure object. {key} is equivalent to {key: key}.

let { name: musicName, artist: artist, id: id} = {
    id347230.name"Sea and sky".artist"Beyond".album"Sea and sky".duration326000.mark8192
}

console.log(id, musicName, artist)
Copy the code
  1. Unmatched attributes will return undefined
let { time } = {
    id347230.name"Sea and sky".artist"Beyond".album"Sea and sky".duration326000.mark8192
}

console.log(time) // undefined
Copy the code
  1. The structure of objects also supports nested destructions
let {id, artists: [a1, a2], artists} = {
    id347230.name"Shukbetta".artists: [{
            name'Monday'
        },
        {
            name'beta'}].duration326000.mark8192
}

 console.log(id) / / 347230
 console.log(a1) // {name: 'shuke '}
 console.log(a2) // {name: 'beta '}
 console.log(artists) // [{name: 'shuke '}, {name:' beta '}]
Copy the code
  1. Nested destructions will return undefined if they do not match, and structuring undefined will return an error
 let {id: {name}} = {
    id347230.name"Shukbetta".duration326000.mark8192
}

console.log(name) // undefined

let {id: { name: {a} }} = { // Error Cannot read property 'a' of undefined
    id347230.name"Shukbetta".duration326000.mark8192
}
Copy the code

Expansion operator (…)

The concept ES6 provides expansion operators that can expand arrays or objects (by removing [] or {})

grammar

let arr = [1.2.3.4]
let arr1 = [...arr, 7] //  [1,2,3,4,7]

let person = { name: 'Ming'.age: 18}
letnewPerson = {... person,address: 'gz'} // {name: 'xiaoming ', age: 18, address: 'gz'}
Copy the code

Pay attention to

  1. The expansion operator of an object is used to add new attributes to an object or to merge objects, with the latter replacing the former if the same attributes are present
let obj = {
    name: 'Ming'.age: 18
}

let obj1 = {
    age: 19.address: 'gz'
}


console.log({... obj, ... obj1,address'sz'}) 
{address: "sz",age: 19,name: "xiao Ming "} */
Copy the code
  1. In deconstruction… Support for residual (REST) operations
let [a, b, ...c] = [1.2.3.4.5]
// a 1
// b 2
// c [3, 4, 5]

let{name, ... otherDetail} = {name'Ming'.age18.address'gz'.hobby: []}// name 'xiaoming'
// otherDetail { age: 18, address: 'gz', hobby: []}
Copy the code
  1. A string is a special array, so you can also use the expansion operator
[...'hello']  // ['h', 'e', 'l', 'l', 'o']
Copy the code
  1. Deconstruction, expansion operators, and REST operations can all be applied to function arguments
 // Parameters use deconstruction to directly get the attributes needed in the object
function sayHello({name,age,city,... otherDetail}{

    console.log('hello! My name is' + name+'this year'+age+', ' + ', from ' + city)
    console.log(otherDetail)
}

let p = {
    name'Ming'.age25.city'shenzhen'.hobby: [].marriedfalse
}

sayHello(p)

// Arrays use expansion operators to pass arguments to functions
function add(x, y{
    console.log(x + y)
}

let arr = [8.17] add(... arr)Copy the code

ES6 adds a lot of APIS to Array

map

The concept iterates through the current array to generate a new array

The syntax map takes a function that takes two arguments. The result map returns is that each element in the array is the value returned by calling the provided function once.

  • Parameter Specifies the value of the current item in the array

  • Parameter Twice iterates the subscript of the current item in the array

let ages = [12.14.18.13.25]
let newAges = ages.map(function (item, index{
        if(item >= 18) {
            return 'adult'  
        }
        return "Minor"  // return returns the value of each item in the new array
})

console.log( newAges) // [" minor ", "minor "," adult ", "minor "," adult "]
console.log( ages) // [12, 14, 18, 13, 25]
Copy the code

filter

The concept iterates through the current array to generate a filtered new array

The syntax map takes a function, and the function takes two arguments. This function preserves the current iteration of the array if it returns true, and filters if it returns false.

  • Parameter Specifies the value of the current item in the array

  • Parameter Twice iterates the subscript of the current item in the array

let ages = [12.14.17.23.18.13.25]

let newArr = ages.filter(function(The item, the index{
    if(item % 2= = =0) {
        return true / / to keep
    }else {
        return false / / delete}})console.log(newArr)
Copy the code

from

The concept iterates through an array to generate a new array

Array.from(arr[, mapFunc, mapThis])

  • Parameter one traverses a number of objects

  • Parameter 2 Map function that is called for each traversal (optional)

  • Parameter three specifies this inside parameter two (optional)

let arr = [1.2.3.4]

let cat = {
    name'white'.age2
}

let newArr1 = Array.from(arr, function(item, index){
    // Item specifies the value of each item in the array
    // index the index of each item in the array
    console.log(index, this)
    return item * 3
}, cat) // Argument 3 is this in the argument 2 method

console.log(newArr1) / /,6,9,12 [3]
Copy the code

*of

Conceptual methods create a new instance of an array with a variable number of parameters, regardless of the number or type of parameters (less used)

grammar

Array.of(7);       / / [7]
Array.of(1.2.3); / / [1, 2, 3]
Array.of(undefined); // [undefined]

Array(7);          // [,,,,,,]
Array(1.2.3);    / / [1, 2, 3]
Array(undefined);  // [undefined]
Copy the code

*copyWithin

The conceptual methods are used to copy elements from one specified location in an array to another specified location in an array. This method modifies the original array (rarely used)

Syntax copyWithin(target[, start[, end]])

  • Argument one specifies the subscript position of the replacement copy array

  • The actual subscript position of parameter two copy is optional by default 0

  • Parameter 3 Length of replacement Optional Value The length from the default start position to the replacement destination position

[1.2.3.4.5.6].copyWithin(2.0) / / [1, 2, 1,2,5,6]
[1.2.3.4.5.6].copyWithin(3.1.2) / /,2,3,2,3,6 [1]
Copy the code

find

The conceptual method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined

Grammar array. The find (mapfuc)

  • Parameter 1: this method is called once when find iterates through each item in the array. This method takes two parameters (the value of the current item, the subscript of the current item)
let array = [0.12.22.55.44]

console.log(array.find((item,index) = > item >= 18))

let todos = [{
            id1.text'learning es6'.completedfalse
        },
        {
            id2.text'learning vue'.completedtrue
        },
        {
            id3.text'learning react'.completedfalse
        },
        {
            id4.text'learning js'.completedfalse},]console.log(todos.find(item= > item.id === 2)) // {id: 2,text: 'Learn vue',completed: true}
Copy the code

findIndex

The conceptual method returns the index of the first element in the array that satisfies the provided test function. Otherwise -1 is returned.

Grammar array. FindIndex (mapfuc)

  • Parameter mapfuc this method is called once as each item in the array is iterated. This method takes two parameters (the value of the current item, the subscript of the current item)
let array = [0.12.22.55.44]

console.log(array.find((item,index) = > item >= 18)) / / 2

let todos = [{
            id1.text'learning es6'.completedfalse
        },
        {
            id2.text'learning vue'.completedtrue
        },
        {
            id3.text'learning react'.completedfalse
        },
        {
            id4.text'learning js'.completedfalse},]console.log(todos.find(item= > item.id === 2)) / / 1
Copy the code

includes

The concept includes() method is used to determine whether an array contains a specified value, returning true if it does and false otherwise.

grammar

const array1 = [1.2.3];

console.log(array1.includes(2)); // true

const pets = ['cat'.'dog'.'bat'];

console.log(pets.includes('cat')); // true

console.log(pets.includes('at')); // false
Copy the code

reduce

The conceptual reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value.

Grammar reducer (mapFunc)

  • The function that takes two arguments (the return value of the last time the function was executed, and the value of the current item)

  • Parameter 2 initalValue Initial reduce value

let price = [1.2.3.4.5.6.7.8.9.10]

console.log(price.reduce(function (reduce, item{
        console.log(item, reduce)
        return item + reduce
})) / / 55


let todos = [{
            id1.text'learning es6'.completedfalse
        },
        {
            id2.text'learning vue'.completedfalse
        },
        {
            id3.text'learning react'.completedtrue
        },
        {
            id4.text'learning js'.completedfalse
        },
    ]

todos.reduce((prevCount, item) = > {

    if(! item.completed) {return prevCount + 1
    }
    return prevCount
}, 0)
Copy the code

*fill

The concept fill() method fills all elements in an array from the start index to the end index with a fixed value. Does not include terminating indexes (less used)

Syntax Fill (val [,start [,end]])

  • Parameter one specifies the value to fill

  • Parameter 2 Start position for filling is optional

  • Parameter 3 Indicates the end position of the fill. The end position is optional

[1.2.3.4.5].fill(7) / /,7,7,7,7 [7]

[1.2.3.4.5].fill(7.2) / /,2,7,7,7 [1]
 
[1.2.3.4.5].fill(7.2.4) / /,2,7,7,5 [1]
Copy the code

Additional Array APIS: developer.mozilla.org/zh-CN/docs/…

A concise way of writing an object

The concept ES6 allows the object to be abbreviated to a key value with the same name as the key-value pair in braces. If the value of key is a function, it can be abbreviated to key(){}

grammar

let name = 'Ming'
let age = 18

let obj = {
    name, // Equivalent to name: name
    age, // equivalent to age
    sayHello() {  SayHello: function(){}
        console.log('123')}}Copy the code

The dynamic key name of the object

The concept ES6 allows the key property of an object to be a dynamic key name using [js expression] in object braces

grammar

let key = 'currentKey'
let obj = {
    [key]: 123.// currentKey: 123
    [key.split(' ').reverse().join(' ')]: 1.// yeKtnerruc: 1
    sayHello() {
        console.log('123')}}Copy the code

Template syntax for strings

Concept ES6 adds a string enhancement using template string syntax to simplify some complex string concatenation

Syntax template strings use backquotes with ${js expression} syntax

` hello! My name is${name}. Next year,${age+1}Years old, from${city}The city. `
/ / equivalent to the
'hello! My name is' + name + '. Next year, ' + (age + 1) + ', ' + ', from ' + city+'the city. ')
Copy the code

Note that template strings support line breaks, and the output string has a line break

`hello
world`
Copy the code

ES6 other apis

Map/Set links: developer.mozilla.org/zh-CN/docs/…

Link: developer.mozilla.org/zh-CN/docs/…

ArrayBuffer link: developer.mozilla.org/zh-CN/docs/…

Merge air transport operator

The concept returns the first value that is not null or undefined

Grammar use??

let name = ""
let age = 0
let sex = "man"
let test = null
let test1 = undefined
let test2 = false

console.log(name || 'Max') // 'Max'
console.log(age || 18) / / 18
console.log(test || 18) / / 18

// null
console.log(name ?? 'Max') / / ""
console.log(age ?? 18) / / 0
console.log(test ?? 18) / / 18

// undefined
console.log(test1 ?? 18) / / 18

// false
console.log(test2 ?? 18) // false
console.log(18 ?? test2) / / 18

// Both are not null or undefined, return the first value
console.log(age ?? sex) / / 0
console.log(sex ?? age) // man

// Or you can link it as many times as necessary
null ?? undefined ?? false ?? 'min'     // false
null ?? ' ' ?? 'min'                     / /"
Copy the code

Optional link operation

Can concept ES2020 be used? The symbol evaluates to optional attributes and returns undefined if the specified optional attribute is null.

Pay attention to? Symbols can only be used in chain calls. Not at? At the end

data? .artist? .name?/ / error
Copy the code
let data = null
Artist: {name: 'yifan ', id: 1000, alias:' yifan '}} */
// Asynchronous data determines whether the specified attribute exists before ES2020
let artist = data && data.artist && data.artist.name
let alias = (data && data.artist && data.artist.alias) || ' '
// ES2020
letartist = data? .artist? .nameletalias = data? .artist? .alias ??' '

p.innerHTML = `${data.artist.name} (${data.artist.alias}) `
Copy the code

Dynamic introduction

Concept If you have a file full of utility features, and some of them may be used infrequently, importing all of their dependencies may be a waste of resources. Now we can use async/await to dynamically import dependencies as needed.

Syntax import(‘ module path ‘)

const doMath = async (num1, num2) => {
  if (num1 && num2) {
    const math = await import('./math.js');
    console.log(math.add(5.10));
  };
};

doMath(4.2); // If doMath is never called './math.js' it will never be executed
Copy the code