可以通过括号符号在 JavaScript 中解构吗?
Possible to destructure in JavaScript via bracket notation?
这不一定是个问题,更多的是 ESLint 错误引起的好奇心,这让我想知道是否有更好的方法来禁用这一行的 ESLint。
考虑下面的代码片段。如果启用了 react/destructuring-assignment 规则,ESLint 会报错,preferring
const { arrayToPrint } = myArrays
到 const arrayToPrint = myArrays[arrayName]
我的问题是,我还没有找到任何相关的参考资料,所以我猜不是,有没有办法将 [arrayName]
移动到在没有引用实际对象的情况下解构的赋值 属性?
const myArrays = {
arrayOne: ['one'],
arrayTwo: ['two'],
arrayThree: ['three'],
}
const arrayPrinter = function arrayPrinter(arrayName) {
const arrayToPrint = myArrays[arrayName]
return arrayToPrint
}
console.log(arrayPrinter('arrayTwo'))
解构可以用 computed property:
const { [arrayName]: arrayToPrint } = myArrays;
一个简单的方法是使用 Object.entries(myArrays)
.
/* example: expected output of console.log(Object.entries(myArrays)[1]) is ["arrayTwo": Array ["two"]]
这不一定是个问题,更多的是 ESLint 错误引起的好奇心,这让我想知道是否有更好的方法来禁用这一行的 ESLint。
考虑下面的代码片段。如果启用了 react/destructuring-assignment 规则,ESLint 会报错,preferring
const { arrayToPrint } = myArrays
到 const arrayToPrint = myArrays[arrayName]
我的问题是,我还没有找到任何相关的参考资料,所以我猜不是,有没有办法将 [arrayName]
移动到在没有引用实际对象的情况下解构的赋值 属性?
const myArrays = {
arrayOne: ['one'],
arrayTwo: ['two'],
arrayThree: ['three'],
}
const arrayPrinter = function arrayPrinter(arrayName) {
const arrayToPrint = myArrays[arrayName]
return arrayToPrint
}
console.log(arrayPrinter('arrayTwo'))
解构可以用 computed property:
const { [arrayName]: arrayToPrint } = myArrays;
一个简单的方法是使用 Object.entries(myArrays)
.
/* example: expected output of console.log(Object.entries(myArrays)[1]) is ["arrayTwo": Array ["two"]]