工作生活

ES6解构赋值

2019-07-01  本文已影响0人  椰果粒

题目

题目1:用解构赋值实现两个变量值互换

let a = "aaa";
let b = "bbb";
[a, b] = [b, a]
console.log(a); // "bbb"
console.log(b); // "aaa"

题目2:用解构赋值实现函数默认参数

function getName({name = "zhangsan"}){
  console.log(name)
}
getName({}) // zhangsan 

概念

解构赋值:从数组或对象中提取出值,并对变量进行赋值。

数组的解构赋值

// 新的声明变量的方式
let [c, d, e] = [1,2,4];
console.log(c); // 1
console.log(d); // 2
console.log(e); // 4

// 从数组中提取值,按照对应的位置,对变量赋值。
let [head, ...tail] = ["a","b","c","d","e"];
console.log(head) // a
console.log(tail) // ["b","c","d","e"]

let [x, y, ...z] = ["xxx"];
console.log(x); // "xxx"
console.log(y); // undefined
console.log(z); // []

如果解构不成功,变量的值就是undefined
如果右边不是数组,就会报错,因为后边不是可遍历的结构

let [m,n] = undefined;  // Uncaught TypeError: undefined is not iterable
// set结构也可以用解构赋值
let [a,b,c] = new Set(["a", "b", "d"])
console.log(c); // "d"
// 另外一种情况
let [a,b,c] = new Set(["a", "b", "b"])
console.log(c); // undefined  

只要数据又iterator接口,都可以采用数组形式的解构赋值
还可以指定默认值,默认值这里,只有右边严格等于undefined,才会生效

let [a="aaa"] = [];
console.log(a); // aaa

let [a="aaa"] = [null];
console.log(a); // null,因为null不严格等于undefined

对象的解构赋值

let {foo, bar, a, b, c} = {bar:"aaa", foo:"bbb"}
console.log(foo)  // bbb
console.log(bar)  // aaa
console.log(a)    // undefined
上一篇下一篇

猜你喜欢

热点阅读