ES6——对象解构和数组解构

    技术2025-03-02  5

    为什么要使用解构功能 在ES5及早期版本中,开发者们为了从对象和数组中获取特定数据并赋值给变量,编写了许多看起来同质化的代码,如下: //从对象中取数据 let options = { repeat:true, save:false };

    let repeat = options.repeat, save = options.save;

    对象解构 对象解构的语法形式是在一个赋值操作左边放置一个对象字面量,如:

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

    注意:如果使用var、let、const解构声明变量,必须要提供初始化程序(也就是等号右侧的值),否则会导致程序抛出语法错误。

    默认值 使用解构赋值表达式时,如果指定的局部变量名称在对象中不存在,那么这个局部变量会被赋值为undefined,如下:

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

    当指定的属性不存在时,可以随意定义一个默认值,在属性名称后添加一个等号(=)和相应的默认值即可:

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

    当使用其他变量名进行赋值时也可以添加默认值,只需在变量名后添加等号和默认值即可:

    let node = { type:"Identifier" }; let {type:localType,name:localName = "bar"} = node; console.log(localType);//"Identifier" console.log(localName);//"bar"

    数组解构 与对象解构的语法相比,数组解构就简单多了,它使用的是数组字面量,且解构操作全部在数组内完成,而不是像对象字面量语法一样使用对象的命名属性:

    let colors = ["red","green","blue"]; let [firstColor,secondColor] = colors; console.log(firstColor);//"red" console.log(secondColor);//"green"

    在解构模式中,也可以直接省略元素,只为感兴趣的元素提供变量名。比如,如果你只想取数组中的第三个值,则不需要提供第一个和第二个元素的变量名称:

    let colors = ["red","green","blue"]; let [ ,,thirdColor] = colors; console.log(thirdColor);//"blue"

    数组解构还有一个独特的用例:交换两个变量的值。在ES5中交换两个变量的值需要引入第三个临时变量,但在ES6的数组解构中,就不再需要额外的变量了,如下:

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

    默认值 也可以在数组解构赋值表达式中为数组中的任意位置添加默认值,当指定位置的属性不存在或其值为undefined时使用默认值:

    let colors = ["red"]; let [firstColor,secondColor = "green"] = colors; console.log(firstColor);//"red" console.log(secondColor);//"green"
    Processed: 0.008, SQL: 9