簡體   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