ES5-ES6-ES7_解构赋值

解构赋值的概念

ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)

传统对变量赋值的方式,以前,为变量赋值,只能直接指定值。

var a = 1;
var b = 2;
var c = 3;

数组的解构赋值——简单的数组解构赋值和嵌套数组的解构赋值

ES6允许写成下面这样。可以从数组中提取值,按照对应位置,对变量赋值 。本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值

var [a,b,c] = [1,2,3];
console.log(a);  //1
console.log(b);  //2
console.log(c);  //3

var arr = [4,5,6];
var [d,e,f] = arr;
console.log(d);     //4
console.log(e);     //5
console.log(f);     //6


//解构赋值不仅适用于var命令,也适用于let和const命令。
let [a1,a2,a3] = [1,2,3];
console.log(a1);  //1
console.log(a2);  //2
console.log(a3);  //3

let arr1 = [4,5,6];
let [a4,a5,a6] = arr1;
console.log(a4);     //4
console.log(a5);     //5
console.log(a6);     //6
   let [foo1, [[bar1], baz1]] = [1, [[2], 3]];
   console.log(foo1)
   console.log(bar1)
   console.log(baz1)

   var arr = [1, [[2], 3]];
   var [foo2, [[bar2], baz2]] = arr;
   console.log(foo2)
   console.log(bar2)
   console.log(baz2)

数组的解构赋值——不完全解构

等号左边的模式,只匹配一部分的等号右边的数组。这种情况下,解构依然可以成功

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

let [ , , third] = ["foo", "bar", "baz"];
third // "baz"

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

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

数组的解构赋值——解构不成功

如果解构不成功,变量的值就等于undefined

let [ftt] = [];
let [bar, foo] = [1];

console.log(ftt);   //undefined
console.log(bar);   //1
console.log(foo);   //undefined

字符串的解构赋值

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

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

//类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。
let {length : len} = 'hello';
len // 5

函数参数的解构赋值

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

function add([x, y]){
    return x + y;
}

//函数add的参数表面上是一个数组,但在传入参数的那一刻,数组参数就被解构成变量x和y。
//对于函数内部的代码来说,它们能感受到的参数就是x和y。
add([1, 2]); // 结果是3,

变量的解构赋值的作用——交换变量的值

var x = 28;
var y = 83;

var [x,y] = [y,x];
console.log(x);
console.log(y);

变量的解构赋值的作用——从函数返回多个值

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

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

变量的解构赋值的作用——提取JSON数据

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

变量的解构赋值的作用——函数参数的定义

function f([x,y,z]) {
    return [x,y,z]
}

var [a, b, c] = f([3,4,5])
console.log(a) //3
console.log(b) //4
console.log(c) //5
function f({x,y,z}) {
    return [x,y,z]
}

var [a, b, c] = f({x:3, y:4, z:5})
console.log(a) //3
console.log(b) //4
console.log(c) //5

猜你喜欢

转载自www.cnblogs.com/LO-ME/p/10586715.html
今日推荐