JavaScript中的数组解构 [英] Array destructuring in 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]
,并将各个元素分配给first
和third
(_
是占位符,从而使其跳过第二个元素).因为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;
还允许使用传播运算符:
Spread operator is also permitted:
let [first, ...rest] = [1, 2, 3];
将1
分配给first
,将[2, 3]
分配给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屋!