美文网首页
ES6的解构

ES6的解构

作者: HW_____T | 来源:发表于2017-09-07 14:35 被阅读0次

注:此篇文章是我参考阮一峰老师的[ECMAScript 6 入门]文章,自己记录的笔记,详细的内容请移步阮一峰老师的文章。

1.解构
  • 数组解构
var [a,,b]=[1,2,3,4,5];
console.log(a)//1
console.log(b)//3
  • 对象解构
var {a,b}={a:1,b:2,c:3}
console.log(a)//1
console.log(b)//2
  • 对象匹配解构
    // 对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。
var { foos: foosz, bars: barsaa } = { foos: "foosz", bars: "bbb" };  
console.log(foosz);  // foosz
console.log(barsaa);//bbb
console.log(foos); error: foo is not defined  
  • 字符串解构
    字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
let {length : len} = 'hello';
len // 5
  • 数值,布尔值解构
    解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

上面代码中,数值和布尔值的包装对象都有toString属性,因此变量s都能取到值。

解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。

let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
  • 函数参数解构
[[1, 2], [3, 4]].map(([a, b]) => a + b);

undefined就会触发函数参数的默认值。

[1, undefined, 3].map((x = 'yes') => x);
// [ 1, 'yes', 3 ]
function move({x = 0, y = 0} = {}) {
  return [x, y];
}

move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
function move({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}

move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]
  • 使用解构的常见场景

(1) 交换变量的值

let x =1;
let y =2;
[x,y]=[y,x];

(2) 从函数返回多个值

//返回一个数组
function rA(){
  return [1,2,3];
}
let [a,b,c] =rA();

//返回一个对象
function rO(){
 return {
    foo : 1,
    foo2: 2
  }
}
let {foo,foo2}= rO()

(3) 提取JSON数据
解构复制对提取JSON对象中的数据尤其有用。

let jsonData={
  id:22,
  name:'wwwt',
  data:[222,333],
  doT:function(){
    return this.name 
  }  
}
let { id,doT,name,data}=jsonData

(4) 遍历Map结构
任何部署了Iterator接口的对象,都可以用for...of循环遍历。Map结构原生支持Iterator接口,配合变量的解构赋值,获取键名和键值就非常方便。

var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world
如果只想获取键名,或者只想获取键值,可以写成下面这样。

// 获取键名
for (let [key] of map) {
  // ...
}

// 获取键值
for (let [,value] of map) {
  // ...
}

相关文章

网友评论

      本文标题:ES6的解构

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