ES6 入门——变量的解构赋值

1.ES6 声明变量的六种方法

ES5 只有两种声明变量的方法:var命令和function命令。

ES6 除了添加letconst命令,另外两种声明变量的方法:import命令和class命令。

所以,ES6 一共有 6 种声明变量的方法。

2.数组的解构赋值

ES6 允许写成下面这样。

let [a, b, c] = [1, 2, 3];

上面代码表示,可以从数组中提取值,按照对应位置,对变量赋值。

本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。下面是一些使用嵌套数组进行解构的例子。

let [x, y] = [1, 2, 3];
x // 1
y // 2
 
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

上面两个例子,都属于不完全解构,但是可以成功。

// 数组的解构赋值
 
const arr = [1, 2, 3, 4];
let [a, b, c, d] = arr;
 
// 更复杂的匹配规则
 
const arr = ['a', 'b', ['c', 'd', ['e', 'f', 'g']]];
 
const [ , b] = arr;  
const [ , , g] = ['e', 'f', 'g']
const [ , , [ , , g]] = ['c', 'd', ['e', 'f', 'g']];
const [ , , [ , , [ , , g]]] = arr; 

 

2.1 扩展运输符...

// 扩展运算符  ...
 
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b'];
const arr3 = ['zz', 1];
const arr4 = [...arr1, ...arr2, ...arr3];
//arr4=[1,2,3,'a','b','zz',1]
 
 
const arr = [1, 2, 3, 4, 5, 6];
const [a, b, ...c] = arr;
//c=[3,4,5,6]

 

2.2默认值 

// 默认值
 
const arr = [1, null, undefined];
const [a, b = 2, c, d = 'aaa'] = arr;
//b=null  只有数组是undefined的时候,才可以匹配被给的数值 

2.3 交换变量 

let a = 20;
let b = 10;
 
[a, b] = [b, a]; 

2.4 ajax请求后,接收函数返回的多个值 

/ 接收多个 函数返回值
 
function getUserInfo(id) {
  // .. ajax
 
  return [
    true,
    {
      name: '小明',
      gender: '女',
      id: id
    },
    '请求成功'
  ];
};
 
const [status, data, msg] = getUserInfo(123);
//status=true  data={name:"小明",gender: "女",id:"123"}   msg="请求成功" 

3.对象的解构赋值 

 

解构不仅可以用于数组,还可以用于对象。

let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
 
// 对象的解构赋值
 
const obj = {
    saber: '阿尔托利亚',
    archer: '卫宫'
};
// 变量名必须和属性名一致
const { saber, archer1 } = obj; 

3.1稍微复杂的解构条件 

const player = {
    nickname: '感情的戏∫我没演技∆',
    master: '东海龙王',
    skill: [{
        skillName: '龙吟',
        mp: '100',
        time: 6000
    },{
        skillName: '龙卷雨击',
        mp: '400',
        time: 3000
    },{
        skillName: '龙腾',
        mp: '900',
        time: 60000
    }]
};
 
const { nickname } = player;
const { master } = player;
const { skill: [ skill1, { skillName }, { skillName: sklName } ] } = player;
 
const { skill } = player;
const [ skill1 ] = skill; 

 

3.2 结合扩展运算符 

// 结合扩展运算符
 
const obj = {
    saber: '阿尔托利亚',
    archer: '卫宫',
    lancer: '瑟坦达'
};
 
const { saber, ...oth } = obj; 

 

对象的合并 

const obj1 = {
    archer: '卫宫',
    lancer: '瑟坦达'
}
 
const obj = {
    saber: '阿尔托利亚',
    ...obj1,
}; 

 

3.3如何对已经申明了的变量进行对象的解构赋值 

let age;
const obj = {
    name: '小明',
    age: 22
};
 
({ age } = obj); 

 

 

 

3.3 对象的解构也可以指定默认值。

let girlfriend = {
    name: '小红',
    age: undefined,
};
 
let { name, age = 24, hobby = ['学习'] } = girlfriend;

 

3.4 提取对象属性

const { name, hobby: [hobby1], hobby } = {
    name: '小红',
    hobby: ['学习', '看书', "玩游戏"]
};

 3.5  获取多个 函数返回值

 
function getUserInfo(uid) {
    // ...ajax
 
    return {
        status: true,
        data: {
            name: '小红'
        },
        msg: '请求成功'
    };
};
 
const { status, data, msg: message } = getUserInfo(123);

 

3.6 编程的练习

针对如下代码,提取start的line,然后在提出end对象中line;

let node = {
    type: "Identifier",
    name: "ES",
    loc: {
        start: ["line", "colume"],
        end: {
            line: 1,
            column: 4
        }
    }
}
let { loc: { start: [start1], end: { line } } } = node; 

 

 4.字符串的解构赋值

字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。

const [a, b, c, d, e] = 'hello';

 

// 字符串的结构赋值
const str = 'I am the bone of my sword'; 
 
const [a, b, c, ...oth] = str;

 

 

提取属性

 

 
// 提取属性
 
const { length, split } = str;

 类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

let {length : len} = 'hello';
len // 5

5.函数参数的解构赋值 

function swap([x, y]) {
    return [y, x];
};
 
let arr = [1, 2];
arr = swap(arr);

 

函数的参数也可以使用解构赋值。

function add([x, y]){
  return x + y;
}
 
add([1, 2]); // 3 

[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]

 

function Computer({
    cpu,
    memory,
    software = ['ie6'],
    OS = 'windows 3.5'
}) {
 
    console.log(cpu);
    console.log(memory);
    console.log(software);
    console.log(OS);
 
};
 
new Computer({
    memory: '128G',
    cpu: '80286',
    OS: 'windows 10'
}); 

 

ES6 的规则是,只要有可能导致解构的歧义,就不得使用圆括号。

不能使用圆括号的情况

以下三种解构赋值不得使用圆括号。

(1)变量声明语句 (2)函数参数   (3)赋值语句的模式

 6.变量的解构赋值用途很多

(1)交换变量的值

let x = 1;
let y = 2;
 
[x, y] = [y, x];

(2)从函数返回多个值

函数只能返回一个值,如果要返回多个值,只能将它们放在数组或对象里返回。有了解构赋值,取出这些值就非常方便。

// 返回一个数组
 
function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();
 
// 返回一个对象
 
function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

 (3)函数参数的定义

解构赋值可以方便地将一组参数与变量名对应起来。

// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
 
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

4)提取 JSON 数据

解构赋值对提取 JSON 对象中的数据,尤其有用。

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};
 
let { id, status, data: number } = jsonData;
 
console.log(id, status, number);
// 42, "OK", [867, 5309]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值