ES6 解构赋值

解构赋值是两个名词:解构,赋值

解构的意义:使数据访问更便捷

对象和数组字面量是js中两种最常用的数据结构,在实际的编码过程中我们常常会定义使用它们,然后有组织的从中提取相关的信息片段,ES6 语法添加了简化了这种操作的新特性:解构。解构是一种打破数据解构,将其拆分为更小部分的过程。

When we fetch an object from API, we need to extract element for our work purpose. In older javascript style we extract each element from an object with a line. If there is 100 element of an object we to had to write 100 lines for extraction but ES6 is a big relief. It helps us to extract multiple elements from an object with a single line.

const student = {
    firstname: ‘David’,
    lastname: ‘fu’,
    country: ‘China’,
    ielts_scores: {
      speaking: 8,
      listening: 7.5,
      writing: 8.5,
      reading: 7.0
    }
};

//Old Style 
const firstname = student.firstname;
const lastname = student.lastname;
const country = student.country;
const ielts_scores = student.ielts_scores;
console.log(`Old method: ${firstname}, ${lastname}, ${country}`) //"Old Style: David, fu, China”


//ES6 Style
const { firstname, lastname, country, ielts_scores } = student;
console.log(`New method: ${firstname} ${lastname} ${firstname}`) //"ES6 Style: David, fu, China"

 

From the above example, Here is an object namedstudent A student has firstnamelastname, country and ielts_score. In the old destructuring method we need to write 4 lines of code to exact all the data but in ES6 we just need only one line.

Different Variable Names:

When we want a different variable name for an object key we only need the colon operator.

{object_key : new_variable_name } = object

const student = {
    firstname: 'David',
    lastname: 'fu',
    country: 'China'
};

const { firstname:firstName, lastname:lastName, country:origin} = student;
console.log(`We are talking about ${firstName} ${lastName}, who came from ${origin}`)
//"We are talking about David fu, who came from China"

(above contents are reference from https://medium.com/infancyit/es6-object-destructuring-16b781b034a5)

在ES5 中我们定义对象是:

let options = {

name: 'David',

age: 20,

address: 'xian'

}

然后从对象中提取数据:

let name = options.name, age = options.age, address = options.address;

 

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

let info = {

name = 'foo',

age: 20

}

let { name, age } = info;

console.log(name); // foo

console.log(age); // 20

在以上代码中,info.name的值被存储在name的变量中,info.age的值被存储在age的变量中,name和age都是声明的局部变量,也是可以从info对象中读取对应属性值。

注意:如果用var, let, const解构声明变量,必须初始化(也就是等号右侧必须有值)

例如:

let { name, age };

var { name, age };

const { name, age };

以上都是语法错误的解构声明。

解构赋值:

let info = {

name = 'foo',

age: 20

},

name = 'david',

age = 30;

// 使用解构语法为多个变量赋值

({ name, age } = info); // 请注意一定要用小括号包裹赋值语句

console.log(name); // foo

console.log(age); // 20

解构赋值表达式(也就是等号=右侧的表达式)如果为null或underfined会导致程序抛出错误,也就是说任何试图读取null或undefined的属性的行为都会触发运行是错误;

默认值:

let node = {

type = "identifier",

name = "foo"

}

let { type, name, value } = node;

console.log(type); // identifier

console.log(name); // foo

console.log(value); // undefined

额为定义的value在对象node上没有值,所以会报出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

为变量设置了默认值true,只有当node上没有该属性或者该属性值为undefined是才生效

Destructuring Assignment in ES6- Arrays

Destructuring assignment is a cool feature that came along with ES6. Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables.

解构不仅可以用于数组,还可以用于对象。

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

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

let colors = [ 'red', 'blue', 'orange'];

let { firstColor, secondColor } = colors;

console.log(firstColor); // red

console.log(secondColor); // blue

此段代码中我们从colors中解构出了 red 和 blue 这两个值,并分别存储在firstColor和secondColor两个变量中,

在解构模式中,我们也可以直接提取自己需要的值,而忽略掉不需要的值,比如你只想要第三个值orange,则你需要提供第三个值即可,而不要提供第一个和第二个值

let colors = [ 'red', 'blue', 'orange'];

let { , , thirdColor } = colors;

console.log(thirdColor); // orange

解构赋值:数组解构也可用于赋值上下文,但不需要使用一对括号包裹表达式,这一点与对象的解构的约定不同

let colors = [ 'red', 'blue', 'orange'],firstColor = 'black', secondColor = 'purple';

[ firstColor, secondColor ] = colors;

console.log(firstColor); // red

console.log(secondColor); // blue

此处的firstColor 和 secondColor 变量已经被定义了。

数组的解构赋值可以参阅:https://dev.to/sarah_chima/destructuring-assignment---arrays-16f

 

更多知识点可以参阅:

http://es6.ruanyifeng.com/#docs/destructuring

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值