ES6学习之变量的解构赋值

时间:2022-12-26 12:17:30

1.数组的解构赋值

let [a, b, c] = ["hello", 1, 2]
console.log(a) //hello
console.log(b) //1
console.log(c) //2

本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。如果解构不成功,变量的值就等于undefined

let [, , third, last, ...rest] = ["foo", "bar", "baz"];
console.log(third) //baz
console.log(last) //undefined
console.log(rest) //[]
// 不完全解构
let [a, b] = ["x", "y", "z"]
console.log(a) //x
console.log(b) //y

//set结构解构
let [c, d] = new Set(["x", "y", "z"]);
console.log(c) //x
console.log(d) //y

只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值。

设置默认值:ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,如果一个数组成员不严格等于undefined,默认值是不会生效的。

let [a = 1] = [undefined];
console.log(a); //1
let [b = 2] = [null];
console.log(b) //null

2.对象的解构赋值:对象的属性没有次序,变量必须与属性同名,才能取到正确的值。若变量没有对应的同名属性,则赋值为undefined

let {name,age} = {name:"fred",age:20};
console.log(name)   //fred
console.log(age)    //20
let {height}={name:"fred",age:20};
console.log(height) //undefined

变量名与属性名不一致写法:

let {name:person} = {name:"fred",age:20}
console.log(person) //fred
console.log(name)   //ReferenceError: name is not defined

注:name是匹配模式,person才是变量,真正被赋值的是name

设置默认值:默认值生效的条件是,对象的属性值严格等于undefined

let {name = "fred"} = {name:undefined}
console.log(name)   //fred
let {age = 20} = {age:null}
console.log(age)    //null

为已声明的变量赋值:

let x;
{x} = {x:1} //SyntaxError: Unexpected token =  
            //因为 JavaScript 引擎会将{x}理解成一个代码块
({x} = {x:1})   //x=1

为变量赋值方法:

let {sin,cos} = Math;
console.log(sin)    //[Function: sin]

数组进行对象属性的解构

let arr = [1,2,3]
let {0:first,[arr.length-1]:last} = arr;
console.log(first)  //1
console.log(last)   //3

3.字符串的解构赋值

const [a,b,c,d] = "hello";  //具有Iterator接口,采用数组形式的解构赋值
console.log(a)  //h
console.log(b)  //e
console.log(c)  //l
console.log(d)  //l
const {length:len} = "hello";   //字符串属性的解构
console.log(len)    //5

4.数值和布尔值的解构赋值

let {toString:value} = 123;
console.log(value); //[Function: toString]
let {toString:s} = true;
console.log(s)  //[Function: toString]

5.用途

交换变量的值

let a = 10;
let b = 20;
[a,b] = [b,a];
console.log(a)  //20
console.log(b)  //10

从函数返回多个值

// 数组
function test1(){
    return [1,2,3]
}
let [a,b] = test1();
console.log(a)  //1
console.log(b)  //2

// 对象
function test2(){
    return {a:20,b:40}
}
let {a:x,b:y} = test2();
console.log(x)  //20
console.log(y)  //40

函数参数的定义

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

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

提取JSON数据

let jsonData = {
    name:"fred",
    age:20
}
let {name,age} = jsonData;
console.log(name,age)

设置函数参数默认值

function person({name ="fred",age=20}){
    
}

遍历Map结构

const map = new Map();
map.set("name","fred");
map.set("age",20);

for(let [key,value] of map){
    console.log(key + "is" + value)
}
// name is fred
// age is 20

输入模块的指定方法

const { SourceMapConsumer, SourceNode } = require("source-map");