Deconstruction of arrays and deconstruction of objects

Deconstruction of arrays and deconstruction of objects

One, the deconstruction of the array

Array:

const arr = [100, 200, 300]
1.1 Deconstruction to get all values

The normal array value is obtained by index:

const iNum1 = arr[0]
const iNum2 = arr[1]
const iNum3 = arr[2]
console.log(iNum1, iNum2, iNum3)
// 100 200 300

Through array destructuring:

const [iNum1, iNum2, iNum3] = arr;
console.log(iNum1, iNum2, iNum3)
// 100 200 300
1.2 Destructure the array to obtain partial values

Get the first value:

const [iNum1] = arr
console.log(iNum1)
// 100

Get the median value:

const [, iNum2] = arr
console.log(iNum2)
// 200

const [, ,iNum3] = arr
console.log(iNum3)
// 300

Get rear data:

const [iNum1, ...rest] = arr
console.log(rest)
// [200 300]
1.3 Destructuring parameters are greater than the length of the array
const [iNum1, iNum2, iNum3, iNum4] = arr
console.log(iNum1, iNum2, iNum3, iNum4)
// 100 200 300 undefined

Set default value:

const [iNum1, iNum2, iNum3, iNum4=123] = arr
console.log(iNum1, iNum2, iNum3, iNum4)
// 100 200 300 123
1.4 Example

Get the root path:

const path = '/root/demo'

method one:

const arr = path.split('/')
console.log(arr[1]);
// root

Way two:

const [,rootdir] = path.split('/')
console.log(rootdir)
// root

Second, object deconstruction

Object:

const obj = {
    
     name: "radish", age: 18, height: 180 }

Conventional way:

const name = obj.name
const age = obj.age
const height = obj.height
console.log(name, age, height)
// radish 18 180
2.1 Deconstruction to get all values
const {
    
    name, age, height} = obj
console.log(name, age, height)
// radish 18 180

Compared with the array destructuring, it will be []replaced with{}

2.2 Deconstruction to obtain a specific value
const {
    
    age} = obj
console.log(age)
// 18

const {
    
    name} = obj
console.log(name)
// radish
2.3 Deconstruction to obtain rear data
const {
    
    name, ...rest} = obj
console.log(name)
console.log(rest)
// radish
// { age: 18, height: 180 }
2.4 Set default values
const {
    
    gender='man'} = obj
console.log(gender)
// man

Guess you like

Origin blog.csdn.net/weixin_44736584/article/details/108865288
Recommended