array destructuring
destructuring
decomposing a structure into its individual parts
解构解决了两件事
- 从结构化的数据批量提取对应的数据, 并且直接把值赋予变量(在我们处理接口返回值的时候尤为好用)
- 便捷的给我们的数据赋予初始值, 不用再写类似这样的三元表达式了: a = a === undefiend ? defaultValue: value;
1
2
3
4
5
6
7
8
9
10var [
{
name: firstname,
email: firstemil = 'nobody@none.com'
},
{
name: secondname,
email: secondemil = 'nobody@none.com'
}
] = getSomeRecords();
Refactoring Code Using Destructuring
1 | // before |
1 | // after |
Spread Operator & Declaring Destrutured
…运算符解决了什么问题?我们不需要去管我们没有显式的指示出来的变量。只要它传了, 那么剩下的我都用…运算符去收集和处理。把不确定性可以更好的管理起来。
1 | // before |
1 | // after |
Declaration & Assignment
1 | // before |
1 | // after |
comma separation
解决的问题是: 我需要跳过其中一个元素,完成解构
1 | // before |
1 | // after |
交换两个元素的值
1 | //before |
1 | var x = 10; |
Parameter Arrays
解构同样可以使用在函数的参数中, 当然,在ES6中,直接支持了函数参数的默认值
1 | // before |
1 | // before |
Nested Array Destructuring
使用解构赋值的时候,一定要注意,是否会触发类型错误, 给一个默认值是一个很棒的方法。
1 | // before |
1 | // after |