ES6:变量的结构赋值

A.数组的结构赋值

普通赋值 VS 结构赋值
let a = 1, b = 2, c = 3;//普通
复制代码
let [a, b, c] = [1, 2, 3];//结构
复制代码
1.结构赋值的本质: 模式的匹配
let [a, [b, [c]]] = [1, [2, [3]]]    
//a -> 1  b->2  c-> 3
复制代码
let [a, b] = [2]    
//a->2  b->undefined (解构失败)
复制代码
let [a, b] = [4, 5, 6]    
//a->4 b->5(不完全解构)
复制代码
let [a] = 7    
//TypeError:7 is not iterable
复制代码
2.支持默认值:当右值是undefined或者为[]时取默认值
let [a = 10] = []              //a-->10
let [b = 10] = [undefined]     //b-->10
let [c = 10] = [null]          //c-->null
let [d = 10] = [20]            //d-->20
复制代码
3.惰性取值,先找匹配,找不到匹配才看默认值
function fn(){
     console.log('find me')
     return 2;
}
let [a = fn()]=[3]    //找到匹配值3 ,a-->3 fn() 不执行 
let [b = fn()]=[]     //find me ,b-->2
复制代码

B.对象的结构赋值

1.对象的赋值没有顺序
let {bar, foo} = {foo:234, bar:123};
console.log(bar, foo);    //123 234
复制代码
2.对象中的模式匹配
let {aa, bb} = {aa : 123, bb : 234}
//等同于
//let {aa : aa , bb : bb} = {aa : 123, bb : 234}
console.log('aa'+aa, 'bb'+bb)    //aa123 bb234
复制代码
{aa:aa} 可以简写为 {aa}
列子
let obj = {
    x : [
        'hello',
        {y :123}
    ]
}
复制代码
let {x : [h, {y: y}]} = obj
//x is not defined  h-->hello  y-->123
复制代码
let {x : [h, {y}]} = obj
//x is not defined  h-->hello  y-->123
复制代码
let {x : x, x : [h, {y}]} = obj
//["hello", {y :123}] "hello" 123
复制代码
小结:数组的结构赋值的模式匹配是对应的位置是有序的,对象是模式依据是key值,是无序的。

C.函数参数的默认值应用

基本使用
//ES5
function Person(name, age){
    if(typeof(age) == 'undefined'){
        age = 18;
    }
    console.log(name, age)
}
//ES6
function Person(name, age = 18){
    console.log(name, age)
}
Person('kiwi');            //kiwi 18
Person('sasa', 12);        //sasa 12
Person('alice', 0);        //alice 0
Person('joe', null);       //joe null
Person('jerry', false);    //jerry false
复制代码
参数作用域
function test(x, x){//var x, var x
    console.log(x)
}
test(3, 4)//4
//添加默认值会自动识别为ES6,形参变为块级作用域
function test1(x, x, z = 4){//let x, let x
    console.log(x)
}
test1(3, 4)//Error
复制代码
注意事项
let a = 10
function fa(b = a){
    console.log(b)
}
fa()//10

function fb(b = a){
    let a = 11;
    console.log(b);
}
fb()//10

function fc(b = c){//这里的 c 全局上没有找到
    let c = 11;
    console.log(b);
}
fc()//c is not defined

function fd(c = c){//let c = c,就是相当于未定义就使用
    let c = 11;
    console.log(c);
}
fd()//SyntaxError
复制代码

D.其他

字符串被解构为字符串类型的对象,转化为类数组
let [a,b,c,d] = 'love'
console.log(a,b,c,d) //l o v e
复制代码
let {length} = '123'
//等同于let {length : length} = '123'
console.log(length) //3 (length指后面的那个)
复制代码
let {toString} = 123
console.log(toString == Number.prototype.toString)//true
复制代码
应用:数据交换
let ff = 1, gg = 2;
[ff, gg] = [gg, ff];
console.log(ff, gg);    //2 1
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值