解构

作者: 云彩上的翅胖 | 来源:发表于2017-02-15 16:24 被阅读0次

解构 将数据结构分解为更小的部分的过程

对象解构

语法

在赋值语句左侧使用对象字面量

let node={
    type:"Identifier",
    name:"foo"
}
let {type,name} = node;

node.type的值被存储到type本地变量中。

node.name的值被存储到name本地变量中。

解构赋值

也可以在赋值时使用解构

let node={
    type:"Identifier",
    name:"foo"
}
let type="qwe";
let name="asdf";
({name,type} = node);
console.log(name);//Identifier
console.log(type);//foo

必须使用圆括号包裹解构赋值语句。因为暴露的花括号会被解析为代码块语句,而块语句不允许在赋值操作符左边出现。圆括号标志了里面的花括号并不是块语句,而应该被解释为表达式。

使用结构表达式进行赋值时,整个表达式的返回值是赋值操作符右边的值。

赋值表达式的右边是nullundefined时会导致一个错误。

默认值

如果所指定的本地变量在对象中没有找到同名属性,那么该变量会被赋值为undefined

在属性名后添加一个等号并指定默认值可以定义一个默认值

let {type,name,value="1"};

当指定了默认值的属性缺失或为undefined的情况下就会使用默认值。

赋值给不同的本地变量名

let node={
    type:"Identifier",
    name:"foo"
}
let {type:localType,name:localName}=node;

这种写法表示取得名为typename的属性并分别存储到名为localTypelocalName的变量

添加默认值的方法不变

嵌套的对象解构

let node = {
    type: "Identifier",
    name: "foo",
    loc: {
        start: {
            line: 1,
            column: 1
        },
        end: {
            line: 1,
            column: 4
        }
    }
};
let {loc:{start}}=node;

每当有一个冒号在解构模式中出现,就意味着冒号之前的标识符代表要检查的位置,冒号右侧的则是赋值的目标。当冒号右侧存在花括号时,表示目标嵌套在更深一层中。

使用不同名称的方法相同。

数组解构

语法

使用数组字面量语法

let colors = ["red", "green", "blue"];
let [firstColor,secondColor]=colors;

数组中被选择的值由它们在数组中的位置决定,与变量的名称无关。没有在解构模式中明确指明的项都会被忽略。数组本身不会有任何变化。

可以使用占位符来获得特定的项。

let colors = ["red", "green", "blue"];
let [,,thirdColor]=colors;

解构赋值

与对象解构赋值类似,但不需要加圆括号。

使用解构赋值互换变量的值

let a=1;let b=2;
[a,b]=[b,a];//a=2,b=1

默认值

默认值的设定与对象解构相同。

嵌套的解构

与对象的嵌套结构类似

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

剩余项

使用 ... 语法可以将数组的剩余的项目赋值给一个指定的变量

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

剩余项只能位于最后,否则会报错。

混合解构

let node = {
    type: "Identifier",
    name: "foo",
    loc: {
        start: {
            line: 1,
            column: 1
        },
        end: {
            line: 1,
            column: 4
        }
    },
    range: [0, 3]
};
let {loc:{start},range:[startIndex]}=node;
console.log(startIndex)//0

参数解构

语法

function setCookie(name, value, { secure, path, domain, expires }) {

// 设置 cookie 的代码
}

setCookie("type", "js", {
secure: true,
expires: 60000
});

解构的参数是必须的

可以给参数默认值来使解构的参数变为可选参数

function setCookie(name, value, { secure, path, domain, expires }={}) {

// 设置 cookie 的代码
}

此时若没有传入第三个参数则name等值全部为 undefined。不会有错误发生。

参数解构的默认值

设置默认值的方法与上面相同。

相关文章

网友评论

      本文标题:解构

      本文链接:https://www.haomeiwen.com/subject/owmqwttx.html