小记3 - 3解构赋值:除对象数组外的其他解构赋值 及用途

2019-12-19  本文已影响0人  ilily

一、字符串的解构赋值

//字符串也能解构赋值,因此时字符串被转换成了一个类似数组的对象(类似于字符串的split方法)
  let str = 'abcdefg';
  let arr = str.split('');
  console.log(arr); // [a, b, c, d, e, f, g]
 
  const [a, b, c, d, e] = 'hello';
  console.log(a, b, c, d, e); // h, e, l, l, o
 
  // 类似数组的对象都有一个length属性,因此还可以对这个属性进行解构赋值
  let { length: len } = 'hello';
  console.log(len); // 5

二、数值和布尔值的解构赋值


// 解构赋值时,如果等号右边是数值和布尔值,则会先转为对象,通过对象的原型进行解构
// 以下代码中,因为数值和布尔值的包装对象都有toString属性,因此s、m都能取到值
  let { toString: s } = 123;
  console.log(s);
  console.log(s === Number.prototype.toString); // true
 
  let { toString: m } = true;
  console.log(m);
  console.log(m === Boolean.prototype.toString); // true
 
// 解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象
// 由于undefined和null无法转为对象,所以对它们进行解构赋值时都会报错
  let { prop: x } = undefined; // 报错:TypeError
  let { prop: y } = null; // 报错:TypeError

三、用途、

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);
// 42, "OK", [867, 5309]
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 接口,配合变量的解构赋值,获取键名和键值就非常方便。

const 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");
8.对于 Set 结构/Generator 函数,使用数组的解构赋值。

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

let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
//fibs是一个 Generator 函数,原生具有 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();
sixth // 5
上一篇 下一篇

猜你喜欢

热点阅读