繁体   English   中英

JavaScript 中的数组解构

[英]Array destructuring in JavaScript

我的 vue-js 应用中有这段代码:

methods: {
    onSubmit() {
      ApiService.post('auth/sign_in', {
        email: this.email,
        password: this.password,
      })
        .then((res) => {
          saveHeaderToCookie(res.headers);
          this.$router.push({ name: 'about' });
        })
        .catch((res) => {
          this.message = res.response.data.errors[0];
          this.msgStatus = true;
          this.msgType = 'error';
        });
    },
  }

在运行Eslint 时,我在这一行收到一条错误消息,提示“使用数组解构”(首选解构)

this.message = res.response.data.errors[0];

什么是数组解构以及如何做到这一点? 请给我一个概念。 我已经研究过了,但无法弄清楚。

解构是在赋值的左侧使用类似结构的语法将右侧结构的元素分配给各个变量。 例如,

let array = [1, 2, 3, 4];
let [first, _, third] = array;

解构数组[1, 2, 3]并将单个元素分配给firstthird_是占位符,使其跳过第二个元素)。 因为 LHS 比 RHS 短,所以4也被忽略了。 它相当于:

let first = array[0];
let third = array[2];

还有一个对象解构赋值:

let object = {first: 1, second: 2, third: 3, some: 4};
let {first, third, fourth: some} = object;

这相当于

let first = object.first;
let third = object.third;
let fourth = object.some;

还允许扩展运算符:

let [first, ...rest] = [1, 2, 3];

会将1分配给first ,将[2, 3]分配给rest

在你的代码中,它说你可以这样做:

[this.message] = res.response.data.errors;

有关prefer-destructuring的文档列出了它认为“正确”的内容。

你可以将该行重写为[this.message] = res.response.data.errors; 并且 es-lint 错误将消失。 请参阅此示例以更好地理解

 var x = { y: { z: { w: [3, 4] } } }; function foo() { [this.a] = xyzw console.log(this.a); } foo() // prints 3

有关数组解构的更多信息,请参见此处

如果您想了解有关 javascript 的信息,请务必在 MDN 上查找。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring

这是一个简单的解构示例:

const [a, b] = ['a', 'b'];

它是自 es6 以来可用的速记,它允许以更速记的方式进行变量赋值。

原来的方式是这样的:

const arr = ['a', 'b'];
const a = arr[0];
const b = arr[1];

而 es6 的方式是这样的:

const arr = ['a', 'b'];
const [a, b] = arr;

现在关于 eslint 错误,我实际上不同意那个错误。 您的代码本身应该没问题。 所以你应该在 Eslint github repo 上提交一个问题来询问为什么该行触发了“prefer-destructuring”警告。

除了给定的解构赋值之外,如果您想获取某些元素,例如数组的第 11 和第 15 个元素,则可以为数组进行对象解构。

在这种情况下,您需要使用带有新变量名的对象属性分配模式 [YDKJS: ES6 & Beyond] ,因为您不能将变量作为数字。

 var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], { 11: a, 15: b } = array; console.log(a, b);

解构是一种从存储在(可能是嵌套的)对象和数组中的数据中提取多个值的方法。 它可以用于接收数据的位置或作为对象的值。 我们将通过一些示例来了解如何使用解构:

数组解构

数组解构适用于所有可迭代值

const iterable = ['a', 'b'];
const [x, y] = iterable;
// x = 'a'; y = 'b'

解构有助于处理返回值

const [all, year, month, day] =
/^(\d\d\d\d)-(\d\d)-(\d\d)$/
.exec('2999-12-31');

对象解构

const obj = { first: 'Jane', last: 'Doe' };
const {first: f, last: l} = obj;
// f = 'Jane'; l = 'Doe'

// {prop} is short for {prop: prop}
const {first, last} = obj;
// first = 'Jane'; last = 'Doe'

在哪里使用解构的例子

// Variable declarations:
const [x] = ['a'];
let [x] = ['a'];
var [x] = ['a'];

// Assignments:
[x] = ['a'];

// Parameter definitions:
function f([x]) { ··· }
f(['a']);


// OR USE IT IN A FOR-OF loop



const arr = ['a', 'b'];
for (const [index, element] of arr.entries()) {
    console.log(index, element);
}
// Output:
// 0 a
// 1 b

解构模式

任何解构都涉及两方

  1. 解构源:要解构的数据,例如解构赋值的右侧。
  2. 解构目标:用于解构的模式。 例如,解构赋值的左侧。

解构目标是以下三种模式之一:

  1. 赋值目标:通常赋值目标是一个变量。 但是在解构赋值中你有更多的选择。 (例如 x)
  2. 对象模式:对象模式的部分是属性,属性值又是模式(递归)(例如 { first: «pattern», last: «pattern» } )
  3. 数组模式:数组模式的部分是元素,元素又是模式(例如 [ «pattern», «pattern» ])

这意味着您可以任意深入地嵌套模式:

const obj = { a: [{ foo: 123, bar: 'abc' }, {}], b: true };
const { a: [{foo: f}] } = obj; // f = 123

**模式如何访问值的内部? **

对象模式在访问属性之前将解构源强制转换为对象。 这意味着它适用于原始值。 使用 ToObject() 执行对对象的强制转换,该方法将原始值转换为包装对象并保持对象不变。 遇到 Undefined 或 Null 时会抛出类型错误。 可以使用空对象模式来检查值是否可强制转换为对象,如下所示:

({} = [true, false]); // OK, Arrays are coercible to objects
({} = 'abc'); // OK, strings are coercible to objects

({} = undefined); // TypeError
({} = null); // TypeError

数组解构使用迭代器来获取源的元素。 因此,您可以对任何可迭代的值进行数组解构。

例子:

// Strings are iterable:
const [x,...y] = 'abc'; // x='a'; y=['b', 'c']


// set value indices
const [x,y] = new Set(['a', 'b']); // x='a'; y='b’;

如果一个值有一个方法,其键是 symbol.iterator 并返回一个对象,那么它就是可迭代的。 如果要解构的值不可迭代,则数组解构会抛出 TypeError

例子:

let x;
[x] = [true, false]; // OK, Arrays are iterable
[x] = 'abc'; // OK, strings are iterable
[x] = { * [Symbol.iterator]() { yield 1 } }; // OK, iterable

[x] = {}; // TypeError, empty objects are not iterable
[x] = undefined; // TypeError, not iterable
[x] = null; // TypeError, not iterable


// TypeError is thrown even before accessing elements of the iterable which means you can use empty Array pattern [] to check if value is iterable
[] = {}; // TypeError, empty objects are not iterable
[] = undefined; // TypeError, not iterable
[] = null; // TypeError, not iterable

可以设置默认值

默认值可以设置为后备

例子:

const [x=3, y] = []; // x = 3; y = undefined

未定义触发默认值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM