JavaScript 中的数组解构 [英] Array destructuring in JavaScript

查看:32
本文介绍了JavaScript 中的数组解构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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';
        });
    },
  }

在运行 Eslint 时,我在这一行看到一个错误,说 使用数组解构"(首选解构):

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;

解构数组[1, 2, 3]并将各个元素分配给firstthird (_> 作为占位符,使其跳过第二个元素).由于 LHS 比 RHS 短,4 也被忽略.相当于:

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;

相当于

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

也允许扩展运算符:

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

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

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;

关于prefer-destructuring 的文档列出了什么它认为是正确的".

The documentation on prefer-destructuring lays out what it considers to be "correct".

这篇关于JavaScript 中的数组解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆