gpt4 book ai didi

javascript - 数组中的嵌套对象 - 对象解构 es6

转载 作者:数据小太阳 更新时间:2023-10-29 06:14:06 24 4
gpt4 key购买 nike

所以我知道您可以像这样进行对象析构:const { item } = data;

还有像这样的数组解构:const [ item ] = data;

您也可以在函数参数中执行此操作,例如:const x = ({ item }) => item;

而且我看到了很多关于它的问题和答案。但是我还没有看到数组中嵌套对象的示例和很好的解释。


const test = [{ count: 1 }];

const [{ count }] = test;

我通常会这样做:

const x = test[0];

const { count } = x;

直到今天在 codepen 中进行测试时,我才发现您可以在同一作业中同时析构它们。

谁能解释一下我在执行 [{ count }] 时发生了什么?因为我正在使用 const [] = test 进行数组破坏,但我没有破坏任何东西,所以显然失败了。如果我在其中 { count } 得到我想要的值。

我无法对其进行足够的分解以了解其工作原理。我假设 [] = testtest[0] 相同,然后我做 { count } = test[0]。但我更想了解它的工作原理。

我确实浏览了一些 MDN 文档和资料,但我找不到对我提到的上述场景的良好解释。

谢谢!

最佳答案

嵌套解构有时会令人困惑。您可以随时查看 Babel compiler获得等效的 ES5 并了解它的工作原理

所以,这段代码:

const test = [{ count: 0 }, { whatever: 1 }, { total: 2 }];
const [{ count }, , { total }] = test

console.log(count, total)

被传输到:

var count = test[0].count;
var total = test[2].total;

如您所见,index = 1 项目是ignored (MDN)我们只解构第 02 索引属性

由于我们讨论的是解构数组对象的主题,因此可以以更高级的方式使用它。您可以像这样在任何索引处解构一个项目:

const test = [{ count: 0 }, { count: 1 }, { count: 2 }];

const { 2: { count } } = test;

console.log(count)

这会获取索引 2 处的计数。此代码等效于:

var count = test[2].count;

请注意,我们在这里使用 {} 而不是 []。这指示编译器在 key 处获取 count:2。您还可以使用这种类型的解构获取数组的长度:

const { length } = test; // same as test.length 

您可以使用 computed object property name 使其更加动态:

const test = [{ count: 0 }, { count: 1 }, { count: 2 }];
const index = 2;

const { [index]: { count } } = test;

console.log(count)

关于javascript - 数组中的嵌套对象 - 对象解构 es6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54870552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com