Javascript-解构

解构赋值

解构赋值语法是一种 Javascript 表达式。通过**解构赋值,**可以将属性/值从对象/数组中取出,赋值给其他变量。

以前我们是怎么赋值的呢?

let a = 10, b = 20;

而使用解构赋值,我们可以更方便地赋值

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

用解构实现基本的变量值的交换

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

基本的数组解构

我们要从数组中提取数据,那么使用解构分配非常简单。

let intro = ["I", "am", "Meowrain"];
const [, , my_name] = intro;
const [me] = intro;
const [,...oh] = intro;
console.log(oh);//["am","Meowrain"]
console.log(me); // I
console.log(my_name); //Meowrain

用函数解构赋值

let add1 = (a,b) => {
    return [a,b]
}
let [c,d] = add1(1,2);
console.log(c,d);

对象解构

在ES6前,我们从对象中提取数据并赋值给新变量,是这么做的

let meowrain = {
    name:"meowrain",
    country:"China",
    age: 18,
    job: "student"
}
let name = meowrain.name;
let country = meowrain.country;
let age = meowrain.age;
let job = meowrain.job;

现在ES6提供了对象解构,我们可以这样写

let meowrain = {
    who:"meowrain",
    country:"China",
    age: 18,
    job: "student"
}
let {who,country,age,job} = meowrain;
console.log(who,country,age,job);

使用新变量名:

let meowrain = {
    who: "meowrain",
    country: "China",
    age: 18,
    job: "student"
}
let { who: guy, country: region, age: years_old, job: work } = meowrain;
console.log(guy, region, years_old, work);

参考链接: