简体   繁体   中英

Array destructuring in JavaScript

I have this code in my vue-js app:

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:

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). Because LHS is shorter than RHS, 4 is also being ignored. 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 .

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".

U can rewrite that line as [this.message] = res.response.data.errors; and that es-lint error will go off. 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. 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.

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:

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

Now in regards to the eslint error, I actually disagree with that one. 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.

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.

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.

 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)
  2. Object pattern: The parts of an object pattern are properties, the property values are again patterns (recursively) (eg { first: «pattern», last: «pattern» } )
  3. Array pattern: The parts of an Array pattern are elements, the elements are again patterns (eg [ «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. Undefined or Null will throw a type error when encountered. 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. Array-destructuring throws a TypeError if the value to be destructured isn't iterable

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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