es6 使用 二三事

1. 在线js 编辑器

http://jsbin.com/?html,js,console,output

2. json 解析:

const student = {
    name:'jsPool',
    age:20,
    scores:{
        math:95,
        chinese:98,
        english:93
    }
}

function showScore(student){
    
    console.log('学生名:' + student.name);
    console.log('数学成绩:' + (student.scores.math || 0 ));
    console.log('语文成绩:' + (student.scores.chinese || 0 ));
    console.log('英语成绩:' + (student.scores.english || 0 ));
}

showScore(student)

3. 用解构完成

const student = {
    name:'jsPool',
    age:20,
    scores:{
        math:95,
        chinese:98,
        english:93
    }
}
function showScore(student){
    const { name,scores:{ math = 0,chinese = 0, english = 0}} = student;
    console.log('学生名:' + name);
    console.log('数学成绩:' + math);
    console.log('语文成绩:' + chinese);
    console.log('英语成绩:' + english);
}
showScore(student)

4. 数组对象的解构

与对象解构的语法相比,数组解构就简单多了,它使用的是数组字面量,且解构操作全部在数组内完成,而不是像对象字面量语法一样使用对象的命名属性。

let list = [221,'Baker Street','London'];
let [houseNo,street] = list;
console.log(houseNo,street);// 221 , Baker Street
复制代码

在上面的代码中,我们从数组 list 中解构出数组索引 0 和 1 所对应的值并分别存储至变量 houseNo 和 street 中。

在数组的解构中,也可以直接省略元素,只为需要的元素提供变量名:

let list = [221,'Baker Street','London'];
let [houseNo,,city] = list;
console.log(houseNo,city);// 221 , London

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值