如何从一个复杂的数据结构中提取数据 es5
在es5中从复杂的数据结构中去挑数据是需要层层的遍历或者是引用,会相当麻烦。 demo: es5从复杂的数据解构中取出我们想要的数据 let arr = ['hello', 'world']
let firstName = arr[0]
let surName = arr[1]
console.log(firstName, surName)
es6
而es6中所谓的更优雅更便捷的方式就是解构赋值。 demo: es6从复杂的数据解构中取出我们想要的数据 let arr = ['hello', 'world']
let [firstName, surName] = arr
console.log(firstName, surName)
简写的方式,新声明的变量必须跟对象属性名一样,如果这个变量跟属性不一样,它解构赋值的时候就不知道你 这个变量要和哪个属性匹配,取哪个值。 let {title: title2, width, height} = options
console.log(title2, width, height)
如果说你不想让这个变量跟属性名一样,就不能简写了。后面的话必须要有一个变量名称。
Object解构赋值基础情况
let options = { title: 'menu', width: 100, height: 200 } let {title, width, height} = options console.log(title, width, height)
默认值的问题
let {title: title2, width = 130, height} = options console.log(title2, width, height) rest
let {title, ...last} = options console.log(title2, last) 复杂的嵌套的数据结构
let options = { size: { width: 100, height: 200 }, items: ['Cake', 'Donut'], extra: true } let {size: {width: width2, height}, items: [item1]} = options console.log(width2, height, item1)
函数参数复杂的时候也可以用解构赋值
Object的解构赋值
Array的解构赋值
let arr = ['a', 'b', 'c', 'd'] 如何跳过某个赋值元素
let [firstName, , thirdName] = arr // 取数组的第一三项 凡是可遍历的对象的数据解构都可以解构赋值,这个可遍历的对象是什么呢,比如我们前面讲的set,map,字符串。 数组或者是字符串,你可以用索引来取某一位或某一项内容。但如果是set,我们是怎么获取某一个元素的?是用 get或者遍历的方式吧,它是不支持索引的。但是利用解构赋值的话,它根本就不用索引的方式,你只要左边写中括 号,默认按照索引的位置排序去取就可以了。不需要显示的指定索引值。根本就不需要关心右边这个数据解构该怎么 取的问题。 let [firstName, , thirdName] = new Set([1, 2, 3, 4])
如果左边不新生成变量,而是把它赋值到一个对象属性上面去,那该怎么做呢?
let user = {name: 's', surname: 't'} 循环 rest
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] let [firstName, curName, ...last] = arr console.log(firstName, curName, last) 前面讲的都是正常的情况,数据足够多,然后给这个赋值。但我们知道赋值的时候你不能保证你的数据一定是有内 容的,这不就是极端或者是异常的情况吗。
let arr = [1, 2, 3] let [firstName, curName, ...last] = arr console.log(firstName, curName, last) // 1 2 [3] let arr = [1, 2] console.log(firstName, curName, last) // 1 2 [] let arr = [1] console.log(firstName, curName, last) // 1 undefined [] let arr = [] console.log(firstName, curName, last) // undefined undefined [] let arr = []
console.log(firstName = 'hello', curName, last) // hello undefined []
es5
user.name = arr[0] user.surname = arr[1] es6
[user.name, user.surname] = [1, 2]
es5
for (let i = 0, item; i < arr.length; i ) { item = arr[i] } es6
let user = {} for (let [k, v] of Object.entries(user)) { console.log(k, v) }
来源:https://www./content-4-658051.html
|