es6的解构赋值

1,变量的解构赋值
//  数组的解构赋值: 一次声明多个变量
let [a2, b2, c2, ] = [1,2,3];
console.log(a2)
console.log(b2)

// 结合扩展运算符
let [head, ...tail] = [1,2,3,4];
console.log(head)
console.log('tail', tail) //[2,3,4]

// 解构赋值允许 设定默认值:
let [ foo01 = true] = []
//  foo01 = true

let [x11, y11 = 'b'] = ['a'];
// x11 = 'a', y11='b'
 

2,对象的解构赋值

let {a11, b11} = {a11:'aa1', b11:'bb2'};
// a= 'aa1'
// 对象的解构 可以指定默认值
let {x1 = 3} = {}
//  x1 = 3

// 2.4,解构赋值的用途
// 1,交换变量的值
let x = 1;
let y = 2;
[x,y] = [y,x]
3,从函数里返回多个值,可以用解构赋值 提取数组和对象里多个值
// 返回一个数组
function example(){
    let [a,b,c] = [1,2,3]
    return [a,b,c]
}
let [a,b,c] = example()
// 返回一个对象
function example2 (){
    return {foo:1, bar:22}
}
let {foo, bar} = example2()

// 3,函数参数的默认值,给定义变量设默认值
function funa (a1=1, b1=2){
    return a1+b1;
}
funa(3) //a1=3, b1=2
4,在组件导入时使用
// 4,导入模块的时候可以用解构赋值,指定导入哪些方法,
import {A1, B2} from  "./utils.js"
// 在utils.js里
export  function A1 () {
    console.log('A1')
}
export  function B2 () {
    console.log('B2')
}
二,模板字符串
// 1,模板字符串可以嵌入变量,可以免除字符串拼接
let x1 = 1;
console.log(`输出值:${x1}`)
//输出值:1

// 2,模板字符串可以调用函数
function fn(){
    return 'hello world'
}
console.log(`输出值为:${fn()}`)
// 输出值为:hello world


// 字符串函数扩展
// 1,includes() :返回布尔值,表示是否找到字符串
let s1 = 'hello ni hao';
console.log(s1.includes('h'))
console.log(s1.includes('ni'))
 
那些必会用到的 ES6 精粹

https://www.imooc.com/article/80680

前端学习之路分享 · 前端躬行记 · 看云

https://www.kancloud.cn/pwstrick/fe-questions/2139313

https://www.cnblogs.com/strick/p/13192977.html

重要

再见2018,你好2019。

https://www.cnblogs.com/netxiaohui/p/10205132.html

https://www.cnblogs.com/netxiaohui/p/14995239.html

原文地址:https://www.cnblogs.com/yizhilin/p/14932508.html