这是一个例子:
const initObject = {
a: 0,
b: 0,
c: 0
}
const { a, ...rest } = initObject
我们从对象中省略了属性 a
,但随后为 const a
分配了一个值,但从未使用过 - 来自 eslint 的错误 (no-unused-vars) 。是否可以完全省略const a
?
最佳答案
一种可能的方法是使用 //eslint-disable-next-line no-unused-vars
例如
// eslint-disable-next-line no-unused-vars
const { a, ...rest } = initObject
The ignoreRestSiblings option is a boolean (default: false). Using a Rest Property it is possible to “omit” properties from an object, but by default the sibling properties are marked as “unused”. With this option enabled the rest property’s siblings are ignored.
例如
/*eslint no-unused-vars: ["error", { "ignoreRestSiblings": true }]*/
// 'a' is ignored because it has a rest property sibling.
const { a, ...rest } = initObject;
有关 no-unused-vars
的更多信息
但是如果您的目标是删除属性 a
,还有另一种方法。
您可以使用delete
运算符。
The JavaScript
delete
operator removes a property from an object
例如
const initObject = {
a: 0,
b: 0,
c: 0
}
const rest = { ...initObject }; // create a shallow copy
delete rest.a;
console.log(rest);
关于javascript - 使用对象解构时省略属性变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56151661/