ES6学习笔记之《变量的解构赋值》

来源:互联网 发布:htc移动网络共享停运 编辑:程序博客网 时间:2024/04/28 00:12

变量的解构赋值

定义:ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。

基础例子:

let [foo, [[bar], baz]] = [1, [[2], 3]];foo // 1bar // 2baz // 3let [ , , third] = ["foo", "bar", "baz"];third // "baz"let [x, , y] = [1, 2, 3];x // 1y // 3let [head, ...tail] = [1, 2, 3, 4];head // 1tail // [2, 3, 4]let [x, y, ...z] = ['a'];x // "a"y // undefinedz // []
高级例子:

只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值

function* fibs() {  let a = 0;  let b = 1;  while (true) {    yield a;    [a, b] = [b, a + b];  }}let [first, second, third, fourth, fifth, sixth] = fibs();//[0,1,1,2,3,5]

let x,y;[ x, y ]= [ 1, x+1 ];x//1y//NaN


这边就要先去学习一下 Generator 函数的语法 (入门新的语言就是这个感觉,看一个知识点会连带很多知识点。。)

Generator函数的语法

默认值:

解构赋值允许指定默认值 ,注意,ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,如果一个数组成员不严格等于undefined,默认值是不会生效的。

let [foo = true] = [];//如果没有设置默认值的话,foo=undefined;foo // truelet [x, y = 'b'] = ['a']; // x='a', y='b'let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
如果一个数组成员是null,默认值就不会生效,因为null不严格等于undefined

let [x = 1] = [undefined];x // 1let [x = 1] = [null];x // null

对象的解构赋值

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

let { foo, bar }= { foo: "aaa", bar: "bbb"};foo//"aaa"bar//"bbb"let {baz}={ foo: "aaa", bar: "bbb"};baz//undefined//如果变量名与属性名不一致,必须写成如下var { foo: baz }={ foo:'aaa' , bar: 'bbb' };baz//"aaa"let obj={ first: 'hello' ,last:'world' };let {first: f, last: l }=obj;f//"hello"l//"world"
也就是说,对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者

let { foo: baz } = { foo: "aaa", bar: "bbb" };baz // "aaa"foo // error: foo is not defined
let命令下面一行的圆括号是必须的,否则会报错。因为解析器会将起首的大括号,理解成一个代码块,而不是赋值语句。

let a;{a}={a:1};//出错let foo;({foo} = {foo: 1}); // 成功let baz;({bar: baz} = {bar: 1}); // 成功

和数组一样,解构也可以用于嵌套结构的对象。

let obj = {  p: [    'Hello',    { y: 'World' }  ]};let { p: [x, { y }] } = obj;x // "Hello"y // "World"
注意,这时p是模式,不是变量,因此不会被赋值。
var node = {  loc: {    start: {      line: 1,      column: 5    }  }};var { loc: { start: { line }} } = node;line // 1loc  // error: loc is undefinedstart // error: start is undefined
上面代码中,只有line是变量,locstart都是模式,不会被赋值。

嵌套赋值的例子:

let obj = {};let arr = [];({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true });obj // {prop:123}arr /
对象的解构也可以指定默认值,默认值生效的条件是,对象的属性值严格等于undefined

var {x = 3} = {};x // 3var {x, y = 5} = {x: 1};x // 1y // 5var {x:y = 3} = {};y // 3var {x:y = 3} = {x: 5};y // 5var { message: msg = 'Something went wrong' } = {};msg // "Something went wrong"var {x = 3} = {x: undefined};x // 3var {x = 3} = {x: null};x // null//如果解构失败,变量的值等于undefined。let {foo} = {bar: 'baz'};foo // undefined//如果解构模式是嵌套的对象,而且子对象所在的父属性不存在,那么将会报错。// 报错let {foo: {bar}} = {baz: 'baz'};
对象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量。

let { log, sin, cos } = Math;
上面代码将Math对象的对数、正弦、余弦三个方法,赋值到对应的变量上,使用起来就会方便很多

字符串的解构赋值

字符串解构赋值时会被转换成了一个类似数组的对象,类似数组的对象都有一个length属性

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 // trues//function toString() { [native code] }let {toString: s} = true;s === Boolean.prototype.toString // true


函数参数的解构赋值

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]

用途:
(1)交换变量的值

let x = 1;let y = 2;[x, y] = [y, x];
(2)从函数返回多个值

// 返回一个数组function example() {  return [1, 2, 3];}let [a, b, c] = example();// 返回一个对象function example() {  return {    foo: 1,    bar: 2  };}let { foo, bar } = example();
(3)函数参数的定义

// 参数是一组有次序的值function f([x, y, z]) { ... }f([1, 2, 3]);// 参数是一组无次序的值function f({x, y, z}) { ... }f({z: 3, y: 2, x: 1});

(4)提取JSON数据

解构赋值对提取JSON对象中的数据,尤其有用。

let jsonData = {  id: 42,  status: "OK",  data: [867, 5309]};let { id, status, data: number } = jsonData;console.log(id, status, number);
(5)函数参数的默认值

指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';

jQuery.ajax = function (url, {  async = true,  beforeSend = function () {},  cache = true,  complete = function () {},  crossDomain = false,  global = true,  // ... more config}) {  // ... do stuff};
(6)遍历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) {  // ...}
(7)输入模块的指定方法
加载模块时,往往需要指定输入那些方法。解构赋值使得输入语句非常清晰。

const { SourceMapConsumer, SourceNode } = require("source-map");




0 0
原创粉丝点击