第21章 变量的解构赋值

1 数组的解构赋值

1.1基本用法

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

  • 只要等号两边的模式相同,左边的变量就会被赋予对应的值(模式匹配
  • 解构不成功,变量的值就等于undefined
  • 等号的右边,转为对象以后不具备 Iterator 接口会报错。
let [foo, [[bar], baz]] = [1, [[2], 3]];
console.log(foo, bar, baz)// 1  2  3:“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。
        
let [x, , y] = [1, 2, 3];
console.log(x, y)// 1  3
let [head, ...tail] = [1, 2, 3, 4];
console.log(head, tail)// 1  [2, 3, 4]
let [x, y] = [1, 2, 3];
console.log(x, y)//1  2:不完全解构,即等号左边的模式,只匹配一部分的等号右边的数组

let [x, y, ...z] = ['a'];
console.log(x, y,z)//a  undefined  []:解构不成功,变量的值就等于undefined

let [foo] = 1;
let [foo] = false;//false is not iterable:如果等号的右边,转为对象以后不具备 Iterator 接口,那么将会报错。
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

let [x, y, z] = new Set(['a', 'b', 'c']);
console.log(x, y, z)//a  b  c:Set 结构,也可以使用数组的解构赋值

let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1:由于数组本质是特殊的对象,因此可以对数组进行对象属性的解构
last // 3

1.2 默认值

  • 只有当一个数组成员严格等于undefined,默认值才会生效
  • 默认值是一个表达式,那么这个表达式是惰性求值
let [x, y = 'b'] = ['a']; // x='a', y='b':只有当一个数组成员严格等于undefined,默认值才会生效
let [x = 1] = [null];
x // null

function f() {
    console.log('aaa');
}
let [x = f()] = [1];
console.log(x)//1:默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到的时候,才会求值。因为x能取到值,所以函数f根本不会执行。

let [x = 1, y = x] = [2];// x=2; y=2
let [x = y, y = 1] = [];// ReferenceError: y is not defined:默认值可以引用解构赋值的其他变量,但该变量必须已经声明。

2 对象的解构赋值

2.1 基本用法

  • 内部机制,变量必须与属性同名:先找到同名属性,然后再赋给对应的变量。{模式,变量}
  • 变量没有对应的同名属性,导致取不到值等于undefined
  • 可以取到继承的属性
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa":对象的属性没有次序,变量必须与属性同名,才能取到正确的值
bar // "bbb"

let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' };//简写

let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa":变量名与属性名不一致:对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量
foo // error: foo is not defined:foo是匹配的模式,baz才是变量。真正被赋值的是变量baz

let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined:变量没有对应的同名属性,导致取不到值,最后等于undefined

const { log } = console;
log('hello') // hello:方便地将现有对象的方法,赋值到某个变量

const obj1 = {};
const obj2 = { foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);
const { foo } = obj1;
foo // "bar":对象的解构赋值可以取到继承的属性,对象obj1的原型对象是obj2

let obj = {//嵌套结构的对象
  p: [
    'Hello',
    { y: 'World' }
  ]
};
let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
p // ["Hello", {y: "World"}]

const node = {
  loc: {
    start: {
      line: 1,
      column: 5
    }
  }
};
let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc  // Object {start: Object}
start // Object {line: 1, column: 5}

// 解构赋值连续写法获取输入值
let obj = { a: { b: { c: 1 } } }
console.log(obj.a.b.c)//1
const { a: { b: { c } } } = obj
console.log(c)//1
const { a: { b: { c: cVal } } } = obj
console.log(cVal)//1

// 报错:等号左边对象的foo属性,对应一个子对象。该子对象的bar属性,解构时会报错。因为foo这时等于undefined,再取子属性就会报错。
let {foo: {bar}} = {baz: 'baz'};//

let obj = {};//嵌套赋值
let arr = [];
({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true });
obj // {prop:123}
arr // [true]

// 正确的写法:避免 JavaScript 将{x}解释为代码块(圆括号的使用条件是???)
let x;
({x} = {x: 1});

({} = [true, false]);
({} = 'abc');
({} = []);

2.2 默认值

  • 默认值生效的条件是,对象的属性值严格等于undefined
var {x = 3} = {x: null};
x // null:默认值生效的条件是,对象的属性值严格等于undefined。

var {x, y = 5} = {x: 1};
x // 1
y // 5:默认值生效

var {x: y = 3} = {};
y // 3:默认值生效
var {x: y = 3} = {x: 5};
y // 5

3 字符串的解构赋值

  • 字符串被转换成了一个类似数组的对象
const [a, b, c, d, e] = 'hello';
a // "h":字符串被转换成了一个类似数组的对象
b // "e"
c // "l"
d // "l"
e // "o"

let {length : len} = 'hello';
len // 5:类似数组的对象都有一个length属性

4 数值和布尔值的解构赋值

  • 先转为数值和布尔值的包装对象
let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true:解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。数值和布尔值的包装对象都有toString属性,因此变量s都能取到值

let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError:undefined和null无法转为对象,所以对它们进行解构赋值,都会报错

5 函数参数的解构赋值

  • 数组形式
  • 对象形式
function add([x, y]){//数组形式
  return x + y;
}
add([1, 2]); // 3

function move({x = 0, y = 0} = {}) {//对象形式:为变量x和y指定默认值
  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 }) {//对象形式:为函数move的参数指定默认值
  return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]

[1, undefined, 3].map((x = 'yes') => x);
// [ 1, 'yes', 3 ]:undefined就会触发函数参数的默认值。

6 用途

(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 数据(接口返回数据重命名)

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]

(5)函数参数的默认值

jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};

(6)遍历 Map 结构(获取键名和键值)

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

for (let [key, value] of map) {//任何部署了 Iterator 接口的对象,都可以用for...of循环遍历
  console.log(key + " is " + value);//Map 结构原生支持 Iterator 接口,配合变量的解构赋值,获取键名和键值就非常方便
}
// 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值