当前位置: 代码迷 >> JavaScript >> 可以通过括号表示法在JavaScript中进行解构吗?
  详细解决方案

可以通过括号表示法在JavaScript中进行解构吗?

热度:19   发布时间:2023-06-03 17:47:22.0

这不一定是一个问题,更多的是通过ESLint错误产生的好奇心,这让我想知道是否有更好的方法只是禁用此行的ESLint。

请考虑下面的代码段。 如果启用了规则,则ESLint将给出错误

const { arrayToPrint } = myArrays to 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')) 

可以使用进行 :

const { [arrayName]: arrayToPrint } = myArrays;

一个简单的方法是使用 。

/* example: expected output of console.log(Object.entries(myArrays)[1]) is ["arrayTwo": Array ["two"]]
  相关解决方案