您的位置:首页 > 其它

ES6---数据解构

2018-01-16 11:28 351 查看
1、数组的解构赋值
let c = [b,a,e] = [1,2,3];
若解构不成立则值为undifiend
2、对象的解构赋值
a、变量名和属性名一样
let { name,gender } = {name: 'jwl',gender: 'man'};
b、变量名和属性名不一样,借助第三方的变量
let city = {name: 'bj',country: 'c'},
{country: c,name: n} = city;
//c='c';n='bj';
c、嵌套解构的值获取
let car_obj = {
tyre: [
'left_tyre',
{r: 'right_tyre'}
]
};
let { tyre: [l,{r}] } = car_obj;
// 此处的tyre是指car_obj中tyre的模式,而非变量,所以tyre为undifiend;
let { a: [l,{r}] } = car_obj;
//此时会报错,因为在对象car_obj中没有a的这种模式。错误信息如下




// 若解构失败,则值为undifiend
3、字符串解构赋值
a、类数组赋值,从左至右一次赋值
let {[a,b]} = '0123456';
//a='0';b='1';
b、类对象赋值
let {length: len} = '0123456';
// len=7;键length是对象的属性,因此在这里可以应用。变量len才是真正的赋值主体。
4、函数参数赋值
a、无默认值
const arr = [1,2,3];
function add ([x,y,z]) {
return x + y + z;
}
add(arr);// 6
b、有默认值
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move();//[0,0]
move({x:1})//[1,0]
//注意:此方法是通过对move的参数(参数为x,y)进行解构,若解构失败就为默认值;

function move ({x,y} = {x:0,y:0}) {
return [x,y];
}
move({x: 3}); // [3, undefined]
move(); // [0, 0]
//此时的参数为对象,而不是x、y,所以若此时会出现undefined
5、**用途**
a、交换变量的值
let x = 1,y = 2;
[x, y] = [y, x];
// 现在的值为[2,1]。原值为[1,2];
b、从函数返回多个值。ES6之前函数返回的值是只能为一个已经命名的值。现在可以直接返回匿名数组或者对象。这样使用时就可以拿来直接使用。
// 返回匿名数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回匿名对象
function car () {
return {
tyre: 4,
color: 'red'
}
}
let {tyre,color} = car();
//tyre=4;color='red'
c、函数参数的一一对应
// 参数是一组无次序的值
function f({x, y, z}) { // x=1;y=2;z=3 }
f({z: 3, y: 2, x: 1});
// 参数是一组有次序的值
function f([x, y, z]) { // x=3;y=2;x=1 }
f([3, 2, 1]);
d、**提取JSON数据**
let json_result = {
id: 666,
code: 200,
status: 'OK',
data: null
};
let {id,code,status} = json_result;
//id等价于json_result.id = 666;
e、设置函数参数的默认值
$.ajax = function (url,{
async = true,
contentType = '',//发送信息至服务器时内容编码类型
beforeSend = function () {/*发送请求前修改函数对象的函数,如添加自定义请求头*/},
complete = function () {/*请求完成后回调的函数*/},
success = function () {},
error = function () {}
}){
// do something
}
f、遍历Map解构
/*
* Map是一种类对象的键值对数据类型;
* map()是js原生数组对象的方法,可用来遍历数组;
*/
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
g、输入模块的指定方法
import {Link} from 'react-router-dom';


本文参考资料:http://es6.ruanyifeng.com/#docs/destructuring
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息