ES6第三章 变量的解构赋值

一、数组的解构赋值

1.从数组中提取值,按照对应的位置,一次赋值

 let [a,b,c] = [1,2,3];
 alert(a);	//1
 alert(b);	//2
 alert(c);	//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 // []

let [foo] = [];		//undefined
let [bar,foo] = [1];	//bar:1 ,foo:undefined

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

如果等式右边不是数组的格式,可能会报错

// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {
    
    };

使用Set结构,也可以使用数组的结构赋值

let [x, y, z] = new Set(['a', 'b', 'c']);
x 		// "a"

2、默认值
解构赋值允许指定默认值。

let [foo = true] = [];
foo // true

let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'

ES6只有当一个数组成员严格等于undefined,默认值才会生效。

let [x = 1] = [undefined];
x // 1

let [x = 1] = [null];
x // null

let [x = 1, y = x] = [];     // x=1; y=1
let [x = 1, y = x] = [2];    // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = [];     // ReferenceError: y is not defined

二、对象的解构赋值

对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

            let {
    
    foo,bar,baz} = {
    
    foo:'a',bar:'b'};
            alert(foo);		//a
            alert(bar);		//b
            alert(baz);		//undefined

对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。

        let {
    
    foo:baz} = {
    
    foo:'aaa',baa:'bbb'};
        alert(baz);		//aaa
        alert(foo);		//报错:foo is not defined

        let obj = {
    
    first:"hello",last:"hello"};
        let {
    
    first:f,last:l} = obj;
        alert(f);		//hello
        alert(l);		//hello

       	let {
    
    foo:foo,bar:bar} = {
    
    foo:'123',bar:'456'};
        alert(foo);		//123
        alert(bar);		//456
  • 默认值
            var {
    
    x = 3} = {
    
    };
            alert(x); // 3

            var {
    
    x, y = 5} = {
    
    x: 1};
            alert(x); // 1
            alert(y); // 5
            
			// “x:”代表x保留了上次的值,如果是“X,”,
			//输出x时会显示undefined
            var {
    
    x: y = 3} = {
    
    };
            alert(x); //1,保留的上次的值
            alert(y); // 3
			
			//此处虽然给x赋值,但是由于x保留的之前的值,
			//x:5的值就被赋给了y
            var {
    
    x: y = 3} = {
    
    x: 5};
            alert(y) // 5

     var {
    
     message: msg = 'Something went wrong' } = {
    
    };
     alert(msg); // "Something went wrong"

要想使默认值生效,需要使它的值为undefined

var {
    
    x = 3} = {
    
    x: undefined};
x // 3

var {
    
    x = 3} = {
    
    x: null};
x // null
  • 注意点
    (1)对于一个已定义的变量,想要用解构赋值,需要在代码外面加一个()。
// 正确的写法
let x;
({
    
    x} = {
    
    x: 1});

三、字符串的结构赋值

字符串被转换成了一个类似数组的对象。

            var [a,b,c,d,e] = 'hello';
            alert(a);
            alert(b);
            alert(c);
            alert(d);
            alert(e);

类似数组的对象都有一个length属性,

var {
    
    length:len} = 'asdfg';
alert(len);

四、数值和布尔值的结构赋值

let {
    
    toString: s} = 123;
s === Number.prototype.toString // true

let {
    
    toString: s} = true;
s === Boolean.prototype.toString // true

由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。

let {
    
     prop: x } = undefined; // TypeError
let {
    
     prop: y } = null; // TypeError

五、函数参数的结构赋值

函数的参数也可以使用解构赋值,在传入参数的那一刻数组参数就被解析成了变量x,y

            function add([x,y]){
    
    
                return x+y;
            }
            alert(add([1,2]));
function move({
    
    x = 0, y = 0} = {
    
    }) {
    
    
  return [x, y];
}

move({
    
    x: 3, y: 8}); // [3, 8]
move({
    
    x: 3}); // [3, 0]
move({
    
    }); // [0, 0]
move(); // [0, 0]

六、圆括号问题

建议只要有可能,就不要在模式中放置圆括号。只有在在赋值语句为非模式部分时,才能使用圆括号。
1、不能使用圆括号的情况
(1)变量声明语句,不能使用圆括号

// 全部报错
let [(a)] = [1];

let {
    
    x: (c)} = {
    
    };
let ({
    
    x: c}) = {
    
    };
let {
    
    (x: c)} = {
    
    };
let {
    
    (x): c} = {
    
    };

let {
    
     o: ({
    
     p: p }) } = {
    
     o: {
    
     p: 2 } };

(2)声明函数不能使用圆括号

// 报错
function f([(z)]) {
    
     return z; }
// 报错
function f([z,(x)]) {
    
     return x; }

(3)赋值语句

// 全部报错
({
    
     p: a }) = {
    
     p: 42 };
([a]) = [5];

七、用途

(1)交换变量

            let x = 1;
            let y = 2;
            [x,y]=[y,x];
            alert(x);
            alert(y);

(2)从函数返回多个值

			function example(){
    
    
                return [1,2,3];
            }
            var [a,b,c] = example();
            alert(a);
            alert(b);
            alert(c);
			function example(){
    
    
                return {
    
    
                    foo:1,
                    baz:2
                };
            }
            var {
    
    foo,baz} = example();
            alert(foo);
            alert(baz);

(2)函数参数的定义

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

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

(5)函数参数的默认值

在这里插入代码片

(6)遍历Map结构

const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
    
    
  console.log(key + " is " + value);
}
// first is hello
// second is world

只获取键值、键名

const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
    
    
  console.log(key + " is " + value);
}
// first is hello
// second is world

猜你喜欢

转载自blog.csdn.net/ladream/article/details/108802534