简体   繁体   English

JavaScript 中的数组解构

[英]Array destructuring in JavaScript

I have this code in my vue-js app:我的 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';
        });
    },
  }

While running Eslint I got an error saying "Use array destructuring" (prefer-destructuring) at this line:在运行Eslint 时,我在这一行收到一条错误消息,提示“使用数组解构”(首选解构)

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

What is array destructuring and how to do this?什么是数组解构以及如何做到这一点? Please provide me a concept on this.请给我一个概念。 I've researched it but could not figure it out.我已经研究过了,但无法弄清楚。

Destucturing is using structure-like syntax on the left-hand-side of an assignment to assign elements of a structure on the right-hand-side to individual variables.解构是在赋值的左侧使用类似结构的语法将右侧结构的元素分配给各个变量。 For exampple,例如,

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

destructures the array [1, 2, 3] and assigns individual elements to first and third ( _ being a placeholder, making it skip the second element).解构数组[1, 2, 3]并将单个元素分配给firstthird_是占位符,使其跳过第二个元素)。 Because LHS is shorter than RHS, 4 is also being ignored.因为 LHS 比 RHS 短,所以4也被忽略了。 It is equivalent to:它相当于:

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

There is also an object destructuring assignment:还有一个对象解构赋值:

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

which is equivalent to这相当于

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

Spread operator is also permitted:还允许扩展运算符:

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

would assign 1 to first , and [2, 3] to rest .会将1分配给first ,将[2, 3]分配给rest

In your code, it says you could do this instead:在你的代码中,它说你可以这样做:

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

The documentation on prefer-destructuring lays out what it considers to be "correct".有关prefer-destructuring的文档列出了它认为“正确”的内容。

U can rewrite that line as [this.message] = res.response.data.errors;你可以将该行重写为[this.message] = res.response.data.errors; and that es-lint error will go off.并且 es-lint 错误将消失。 See this example for better understanding请参阅此示例以更好地理解

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

For more information about array destructuring please see here有关数组解构的更多信息,请参见此处

Always look things up on MDN if you want to find out about javascript things.如果您想了解有关 javascript 的信息,请务必在 MDN 上查找。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring

Here's a simple example of destructuring:这是一个简单的解构示例:

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

Its a shorthand available since es6 that allows doing variable assignment in a more shorthand way.它是自 es6 以来可用的速记,它允许以更速记的方式进行变量赋值。

The original way would be like:原来的方式是这样的:

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

And the es6 way would be like:而 es6 的方式是这样的:

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

Now in regards to the eslint error, I actually disagree with that one.现在关于 eslint 错误,我实际上不同意那个错误。 Your code by itself should be fine.您的代码本身应该没问题。 So you should file an issue on the Eslint github repo to ask about why that line is triggering the "prefer-destructuring" warning.所以你应该在 Eslint github repo 上提交一个问题来询问为什么该行触发了“prefer-destructuring”警告。

Beside of the given destructuring assignments , you could take an object destructuring for an array if you like to take certain elements, like the 11th and 15th element of an array.除了给定的解构赋值之外,如果您想获取某些元素,例如数组的第 11 和第 15 个元素,则可以为数组进行对象解构。

In this case, you need to use the object property assignment pattern [YDKJS: ES6 & Beyond] with a new variable name, because you can not have variables as numbers.在这种情况下,您需要使用带有新变量名的对象属性分配模式 [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);

Destructuring is a method of extracting multiple values from data stored in (possibly nested) objects and Arrays.解构是一种从存储在(可能是嵌套的)对象和数组中的数据中提取多个值的方法。 It can be used in locations that receive data or as the value of objects.它可以用于接收数据的位置或作为对象的值。 We will go through some examples of how to use destructuring:我们将通过一些示例来了解如何使用解构:

Array Destructuring数组解构

Array destructuring works for all iterable values数组解构适用于所有可迭代值

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

Destructuring helps with processing return values解构有助于处理返回值

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

Object Destructuring对象解构

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'

Examples of where to use Destructuring在哪里使用解构的例子

// 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

Patterns for Destructuring解构模式

There are two parties involved in any destructuring任何解构都涉及两方

  1. Destructuring Source: The data to be destructured for example the right side of a destructuring assignment.解构源:要解构的数据,例如解构赋值的右侧。
  2. Destructuring Target: The pattern used for destructuring.解构目标:用于解构的模式。 For example the left side of a destructuring assignment.例如,解构赋值的左侧。

The destructuring target is either one of three patterns:解构目标是以下三种模式之一:

  1. Assignment target: Usually an assignment target is a variable.赋值目标:通常赋值目标是一个变量。 But in destructuring assignment you have more options.但是在解构赋值中你有更多的选择。 (eg x) (例如 x)
  2. Object pattern: The parts of an object pattern are properties, the property values are again patterns (recursively) (eg { first: «pattern», last: «pattern» } )对象模式:对象模式的部分是属性,属性值又是模式(递归)(例如 { first: «pattern», last: «pattern» } )
  3. Array pattern: The parts of an Array pattern are elements, the elements are again patterns (eg [ «pattern», «pattern» ])数组模式:数组模式的部分是元素,元素又是模式(例如 [ «pattern», «pattern» ])

This means you can nest patterns, arbitrarily deeply:这意味着您可以任意深入地嵌套模式:

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

**How do patterns access the innards of values? **模式如何访问值的内部? ** **

Object patterns coerce destructuring sources to objects before accessing properties.对象模式在访问属性之前将解构源强制转换为对象。 That means that it works with primitive values.这意味着它适用于原始值。 The coercion to object is performed using ToObject() which converts primitive values to wrapper objects and leaves objects untouched.使用 ToObject() 执行对对象的强制转换,该方法将原始值转换为包装对象并保持对象不变。 Undefined or Null will throw a type error when encountered.遇到 Undefined 或 Null 时会抛出类型错误。 Can use empty object pattern to check whether a value is coercible to an object as seen here:可以使用空对象模式来检查值是否可强制转换为对象,如下所示:

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

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

Array destructuring uses an iterator to get to the elements of a source.数组解构使用迭代器来获取源的元素。 Therefore, you can Array-destructure any value that is iterable.因此,您可以对任何可迭代的值进行数组解构。

Examples:例子:

// 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’;

A value is iterable if it has a method whose key is symbol.iterator that returns an object.如果一个值有一个方法,其键是 symbol.iterator 并返回一个对象,那么它就是可迭代的。 Array-destructuring throws a TypeError if the value to be destructured isn't iterable如果要解构的值不可迭代,则数组解构会抛出 TypeError

Example:例子:

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

Default values can be set可以设置默认值

Default values can be set as a fallback默认值可以设置为后备

Example:例子:

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

Undefined triggers default values未定义触发默认值

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

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