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